Date Arithmetics in XSLT 2
Now here’s something I didn’t know: XSLT 2 and XPath actually support date arithmetic! Took me a while to figure it out, but here’s how it works.
First, all your dates will have to be in ISO-8601 format. For dates only it looks like this:
YYYY-MM-DD and for dates and times, like this:
YYYY-MM-DDTHH:mm:SS.sssZ. There’s a few other formats, but these are the ones that probably cover all use cases.
In order to make use of all the functions regarding date and time, the values will have to be converted into the appropriate types. They data types are defined in the XMLSchema namespace http://www.w3.org/2001/XMLSchema and are:
xs:datea single date
xs:dateTimea combination thereof
In order to use them, declare the
xs namespace in your stylesheet:
Then you have several ways of creating instances of the above variables:
But there’s more. In addition of the data types that represent points in time, a data type to represent durations exists:
xs:duration. In its string representation it looks a bit funny. The “P” indicates “period”, and “T” stands for “time”:
P1Y2M3DT4H5M13S (meaning: 1 year, 2 months, 3 days, 4 hours, 5 minutes, and 13 seconds). Other than that, I found the
xs:duration data type fidgety and hard to use. Part of that has to do with certain ambiguities that make it almost impossible to use arithmetic operations on them. However, extracting information from duration instances is easy:
The return values of the
*-from-duration() methods can be used to perform calculations.
Once you have your dates and times in the correct datatype, you can perform arithmetic using the familiar operands
+ - * /. Almost all operations return instances of
xs:duration that can
I hope these notes are useful to anybody who has to deal with dates and times in XSLT. Unfortunately, I found most of the documentation on the web incomplete or more confusing than helpful. XSLT, 2nd Edition turned out to be very helpful and I recommend it to every developer working with XSLT and XML.
blog comments powered by Disqus