Durations

An important attribute/variable type when dealing with dates and times is the Duration type, which is used to hold periods of time, such as 1 year, minus 10 days, or 2 hours.

A duration object can be created in a similar way:

duration = DateTimeUtil.createDuration("P1Y");		// 1 year
duration = DateTimeUtil.createDuration("-P10D");		// minus 10 days
duration = DateTimeUtil.createDuration("PT2H");		// 2 hours
duration = DateTimeUtil.createDuration("PT23.456S");	// 23.456 seconds
duration = DateTimeUtil.createDuration("P1DT2H");	// 1 day and 2 hours

When constructing a period of time from a string, always begin with a P for period. Then add nY, nM, or nD, where n is a number of years, months, or days. Any fields that are zero can be omitted. If there is any time component to the Duration, a T must follow the date parts, followed by nH, nM, or nS for specifying hours, minutes, or seconds.

A leading minus sign can be used to create a negative duration. This can be used with the add() method to subtract a time period. The Duration type can also be created by specifying each of the components as integers with a flag to say whether the duration is positive:

duration = DateTimeUtil.createDuration(true, 1, 0, 0, 0, 0, 0);	// 1 year
duration = DateTimeUtil.createDuration(false,0, 0,10, 0, 0, 0);	// minus 10 days
duration = DateTimeUtil.createDuration(true, 0, 0, 0, 2, 0, 0);	// 2 hours
duration = DateTimeUtil.createDuration(true, 0, 0, 0, 0, 0, 23.456);	// 23.456 seconds
duration = DateTimeUtil.createDuration(true, 0, 0, 1, 2, 0, 0);	// 1 day and 2 hours