Comparing Dates and Times

In order to compare two date/time types, either the compare() or equals() method should be used. The equals() method is just a wrapper around the compare() method. The compare() method should be used to compare items that either do or do not have a timezone. The method still works if the date/times are more than 14 hours apart, but if they are less than 14 hours apart, the result is deemed to be indeterminate.

An example of using the compare()method to compare two date fields is shown below:

// Verify that end date is greater than start date
if (enddate.compare(startdate) == DatatypeConstants.GREATER)
{
     // End date is greater than start date
}

Do not use the XMLGregorianCalendar compare() method in the same way you would use the compareTo() method to compare BigInteger and BigDecimal objects due to the possibility of it returning INDETERMINATE. To check for greater than or equals, use the following:

// Verify end date is greater than or equal to start date
if (enddate.compare(startdate) == DatatypeConstants.GREATER  ||
enddate.compare(startdate) == DatatypeConstants.EQUAL)
{
     // End date is greater than or equal to start date
}

Using the following will also include the INDETERMINATE result:

// Verify end date is greater than or equal to start date
if (enddate.compare(startdate) != DatatypeConstants.LESSER)
{
     // End date is greater than or equal to start date – OR INDETERMINATE!!
}

The XMLGregorianCalendar class does not provide a method for finding the difference between two XMLGregorianCalendar objects, so one is provided in ScriptUtil. To find out how many days have elapsed since the start of the year, write:

// Calculate date of first day of the year by getting current date
//   and setting day and month to 1
var startOfYear = DateTimeUtil.createDate();
startOfYear.setDay(1);
startOfYear.setMonth(1);
// get today’s date
var today = DateTimeUtil.createDate();
// Subtract the start of year from today to work out how many days have elapsed
var duration = ScriptUtil.subtract(today, startOfYear);
// Extract the days from the duration type and add 1
dayOfYear = duration.getDays() + 1;

You can read about the different methods that are available on the date/time attributes in Business Data Scripting.