Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
Arithmetic Using Durations
As well as being used for conventional arithmetic with numbers, the arithmetic operators are used to perform certain operations on dates, times, and durations. Not all combinations make sense; for example, it's sensible to add 3 days to a date, but it isn't sensible to add two dates.
There's a table in the XPath 2.0 specification that lists all the combinations of operators and operands that are permitted, and the number that involve dates, times, and durations is alarmingly large. But appearances are deceptive: on closer examination, it turns out that these are all permutations on a small number of themes. The number of permutations is large because it involves:
In fact, all the options boil down to five basic categories:
Expression | Meaning |
date/time +|- duration | Returns a date/time that is a given duration after or before the supplied date/time. For example, 2008-12-31 plus three days is 2009-01-03 . |
duration +|- duration | Adds or subtracts two durations to give another duration. For example, one hour plus two hours is three hours. |
duration *|div number | Multiplies a duration by a numeric factor, or divides it by a numeric factor, to give another duration. For example, one month times 3 is three months. |
date/time – date/time | Determines the interval between two dates/times, as a duration. For example, 2009-01-03 minus 2008-12-31 is three days. |
duration div duration | Determines the ratio between two durations, as a number. For example PT12H divided by PT10 M is 72. |
In each of these cases the following rules hold:
The following sections examine each of the four cases in a bit more detail.
Date/Time Plus Duration
This section covers the following combinations of operands:
Operand 1 | Operand 2 | Result |
xs:date | xs:yearMonthDuration | xs:date |
xs:date | xs:dayTimeDuration | xs:date |
xs:dateTime | xs:yearMonthDuration | xs:dateTime |
xs:dateTime | xs:dayTimeDuration | xs:dateTime |
xs:time | xs:dayTimeDuration | xs:time |
The allowed operators are
+
and
-
. If the operator is
+
, then the operands may appear in either order; if it is
-
, then the date/time must be the first operand and the duration the second. Subtracting a positive duration has the same effect as adding a negative duration, and vice versa.