xslt - subtracting days

Here is a demonstration how to do this in XSLT 2.0:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output method="text"/>

 <xsl:template match="/">
  <xsl:variable name="vToday" select="current-date()"/>

  Today is: <xsl:sequence select="$vToday"/>
  30 days ago it was: <xsl:sequence select=
    "$vToday -30*xs:dayTimeDuration('P1D')"/>
  365 days ago it was: <xsl:sequence select=
    "$vToday -365*xs:dayTimeDuration('P1D')"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the wanted, correct result is produced:

  Today is: 2010-10-07-07:00
  30 days ago it was: 2010-09-07-07:00
  365 days ago it was: 2009-10-07-07:00

Yes, with XSLT 2.0 it is possible, and very easy to do.

There are a lot of Date/Time/Duration functions in XPATH 2.0, which are part of XSLT 2.0.

This example subtracts 1 day from the date 2010-01-01 to produce 2009-12-31:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:template match="/">
  <xsl:value-of select="xs:date('2010-01-01') - xs:dayTimeDuration('P1D')" />
</xsl:template>
</xsl:stylesheet>

Well, XSLT can split strings and parse numbers, so yes, it would be "possible".

However, it would be much easier and efficient if you could use extension functions and implement that in another language. If and how that works depends on the XSLT engine used, however.

EXSLT may have everything you need: http://www.exslt.org/date/functions/add/index.html

Tags:

Math

Date

Xslt