Date minus another date in xslt

Hope someone can help. I am trying to compare 2 dates inside an XML file and use XSLT to calculate:

For example, I have 2 dates in XML: 2011-05-23 and 2011-04-29. I want to do the calculations inside XSLT, as shown below:

('2011-05-23' - '2011-04-29') * 30 = 24 * 30 = 720

Can anyone shed some light?

+3
source share
3 answers

XSLT 2.0 Solution

<?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="days-from-duration(
                                         xs:date('2011-05-23')
                                         - xs:date(xs:date('2011-04-29'))
                      )*30"/>
</xsl:template>
</xsl:stylesheet>

Productivity: 720

  • Function
  • xs:date() Defines dates that can be used to perform date operations.
  • Subtracting the second date from the first, we get xdt:dayTimeDuration P24D(24 days)
  • days-from-duration()retrieves the days component from xdt:dayTimeDuration(24)
  • then you can use this number to perform normal spatial (e.g., 24*30=720)
+2

, EXSLT - date: difference. , , , XSLT.

, , XML Schema Part 2: Datatypes Second Edition, , , , (, ), , : "P24D" ).

+1

, :

<xsl:template name="calcseconds">
  <xsl:param name="date" />
  <xsl:value-of select="(((substring($date,1,4) - 1970) * 365)+floor((substring($date,1,4) - 1970) div 4)+substring('000,031,059,090,120,151,181,212,243,273,304,334,365',substring($date,6,2)*4-3,3)+(substring($date,9,2)-1)+(1-floor(((substring($date,1,4) mod 4) + 2) div 3))*floor((substring($date,6,2)+17) div 20))*86400+(substring($date,12,2)*3600)+(substring($date,15,2)*60)+substring($date,18,2)" />
</xsl:template>

<xsl:template name="calcdays">
  <xsl:param name="date" />
  <xsl:value-of select="(((substring($date,1,4) - 1970) * 365)+floor((substring($date,1,4) - 1970) div 4)+substring('000,031,059,090,120,151,181,212,243,273,304,334,365',substring($date,6,2)*4-3,3)+(substring($date,9,2)-1)+(1-floor(((substring($date,1,4) mod 4) + 2) div 3))*floor((substring($date,6,2)+17) div 20))" />
</xsl:template>

They are a bit of a sip, but they will calculate the number of seconds / days since midnight on January 1, 1970 as an integer, which can then be done using arithmetic. They rely on the date format yyyy-mm-dd hh:mm:ss, but manipulating the parameters of the substring calls should allow you to handle the dates in whatever format you need.

+1
source

All Articles