XSLT 2.0 – More on Dates

Dates.  The “when” of it all.  Working with dates can be frustrating when building client side applications for SharePoint due to the limitations of XSLT 1.0.   Our resident CAPS and XSLT 2.0 expert, Steve Evangelista, blogged a while back about how much easier it is to format dates with our new CAPS service because you can leverage XSLT and XPath 2.0 functions. Having recently helped Steve with a project to create a complicated Gantt chart for resource management, I wanted to take a moment to repeat Steve’s message and also let all of you know how powerful and easy it is to perform date calculations with XSLT 2.0.

One of the first things we need to do is make sure we properly reference the XML namespaces we’ll need to make use of in our xsl:stylesheet node; namely:

The first thing you have to do when with working with dates in XSLT 2.0 is to make sure you recast your date values from your underlying XML, which are all strings, to “date”, “time” and/or “dateTime” types depending on your needs.

You are now ready to do some calculations.  Lets start with a common scenario — finding the difference between two dates:

<xsl:value-of “select=”xs:dateTime(DateTime1)-xs:dateTime(DateTime2)” />

DateTime1 and DateTime2 are two date values from your data in the format of  “yyyy-MM-ddThh:mm:ss” for the dateTime type.  If you’re only interested in dates then use xs:date and if you are only interested in time, use xs:time instead of xs:dateTime.

This gets you a raw value, but we can get what we’re really after by wrapping that calculation in another XPath function.

<xsl:value-of select=”days-from-duration(xs:dateTime(DateTime1)-xs:dateTime(DateTime2))” />

The XPath function “days-from-duration” converts the raw results of our date calculation into something meaningful for your grid display or chart.

If we were only interested in the number of hours, we could have used the XPath function “hours-from-duration”.

It’s that easy.  No need to use any complicated XSLT 1.0 templates, depend on EXSLT libraries or write javascript.   All you need to do is include these XSLT 2.0 functions in XSL  stylesheets that you can apply to your CAPS requests’ XML output.

The w3schools.com website is a great place to learn more about XML, XSLT & XPath. For a listing of XPath 2.0 date/time/duration functions you can go directly to this page:


Have fun and keep building.

Comments are closed.