Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt - subtracting days

Tags:

date

math

xslt

Is it possible with xslt to take a date field and subtract N number of days from it? If so, can you please provide me an example?

like image 595
MattM Avatar asked Oct 07 '10 19:10

MattM


2 Answers

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>
like image 123
Mads Hansen Avatar answered Sep 27 '22 20:09

Mads Hansen


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
like image 32
Dimitre Novatchev Avatar answered Sep 27 '22 18:09

Dimitre Novatchev