Using Date and Time Types with Durations

One important point to be aware of is that the date/time (XMLGregorainCalendar) objects are not immutable, so the add() and setXXX() methods update the object that the method is on, rather than return a new value.

To add 2 hours onto a Datetime, write:

datetime.add(DateTimeUtil.createDuration(“PT2H”));

Not:

datetime = datetime.add(DateTimeUtil.createDuration(“PT2H”));

The second code results in datetime being set to null, since the add() method does not return a value. Duration objects are Immutable, like BigDecimal and BigInteger objects.

If you want to subtract a time period from a date or time type, you can add a negative duration. This is the same as in normal arithmetic where there are two ways of taking 2 from 10. The result of 10 - 2 is the same as 10 + -2. In order to subtract durations, we must use the format of adding a negative amount. The following example calculates 1 year ago.

var date = DateTimeUtil.createDate();	date.add(DateTimeUtil.createDuration("-P1Y"));

The following example calculates a datetime corresponding to 36 hours ago.

var datetime = DateTimeUtil.createDatetime();	datetime.add(DateTimeUtil.createDuration(false,0,0,0,36,0,0));