Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating number of days from two dates in XML with XSLT

Tags:

date

xml

xslt

I've been going on for about 5 hours now, trying exactly EVERY example found on Google found with the serach term "xml xslt calculate number of days between dates" that I could find to just take two dates from "date.xml" file and calculating the days between the dates, in format "YYYY-MM-DD" (example below doesn't have this format, but it's the only format I need)

I finally found this page:: https://forums.oracle.com/thread/2432132

Where the solution can be verified at: http://xslttest.appspot.com/

But, saving the "date.xml/date.xslt" on localhost trying to open the page in Internet Explorer, Google Chrome or Firefox either shows error or nothing at all and as it's always seem to have been - no information what is wrong. The same happens when the file is on a webserver.

So, why can't I try out a simple example that I've found that everyone says has the solution or what am I doing wrong?

XML File from the above example:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="date.xslt"?>

<root>
    <date1>2012-01-11T00:00:00.000-05:00</date1>
    <date2>2012-01-15T00:00:00.000-05:00</date2>
</root>

XSLT File from the above example:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet  version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions">

<xsl:template match="/">
    <xsl:variable name="date1" select="xs:dateTime(/root/date1)"/>
    <xsl:variable name="date2" select="xs:dateTime(/root/date2)"/>
    <xsl:value-of select="fn:days-from-duration($date2 - $date1)"/>
</xsl:template>

</xsl:stylesheet>

Adding this to the XSLT verifier, it shows the right value "4" days between these two dates.

I want to be able to just create a document that actually can do calculations, whether they are dates or numbers but it's seems impossible at this moment. Get number of dates, then do some calculation with that value.

like image 768
Deukalion Avatar asked Dec 10 '13 12:12

Deukalion


1 Answers

Your stylesheet is using XSLT version 2.0, browsers only support XSLT version 1.0. And data types like xs:dateTime and functions like days-from-duration are not supported in XSLT version 1.0. So you need to run your XSLT 2.0 with an XSLT 2.0 processor like Saxon 9 (for Java or .NET) or XmlPrime (for .NET) or with Saxon CE (in the browser).

If you want to use XSLT 1.0 with EXSLT then the test http://home.arcor.de/martin.honnen/xslt/test2013121001.xml using the http://www.exslt.org/date/functions/difference/date.difference.template.xsl works flawlessly for me with actual versions of Firefox, Opera and IE.

like image 138
Martin Honnen Avatar answered Oct 12 '22 16:10

Martin Honnen