How to convert ticks into a readable datetime with XSLT?

By : MrFox
Source: Stackoverflow.com
Question!

I have an XML with timestamps like this:

<node stamp="1236888746689" />

And I would like to display them in the result HTML as date with time. Is there a way to do it with XSLT (any Version)?

EDIT: I am using XSLT2.0 with Saxon9. The base date is 1970-01-01 0:00.

By : MrFox


Answers

You take the date 1970-01-01T00:00:00 and add as many milliseconds as the value of the stamp tells you:

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns="http://www.w3.org/TR/xhtml1/strict">

    <xsl:template match="node">
        <xsl:value-of
select='xs:dateTime("1970-01-01T00:00:00") + @stamp * xs:dayTimeDuration("PT0.001S")'/>
    </xsl:template>

</xsl:stylesheet>
By : f3lix


Belated answer, yes, I know, but I couldn't find the one I was looking for here, so I thought I'd pay it forward with my solution.

My XML was a few nodes dumped from Drupal using export_node and drush. I was using the xslt processor in PHP5, which only supports xslt 1.0. Some EXSLT functions appear to be supported, but I couldn't tell whether my syntax was wrong or the function I was trying to use was not supported. Anyway, the following worked for me. I used the example code from w3schools.com, but added a line right after declaring the xsltprocessor, like below:

$xp = new XsltProcessor();
$xp->registerPHPFunctions();

PHP has a trivial function for date conversion, so I cheated and used the PHP processor, since I was already using it to transform my xsl.

<xsl:for-each select="node_export/node">
  <xsl:value-of select="php:function('date', 'n-j-y', number(timestamp))"/>
</xsl:for-each>

Hope this helps someone out there. I was banging my head for quite a while as I worked this one out.

By : Michael


If you wanted to use an XSL 1.0 processor that does not support the EXSLT date and time functions this is non-trivial, but it has been done.

You can have a look at Katy Coe's XSLT 1.0 implementation of the "iso-from-unix" function. It's part of a rather huge "free for non-commercial use" set of date and time functions she created.

However, your XSL processor must support the "http://exslt.org/functions" namespace for this implementation to work. Other than that there is no dependency on EXSLT.

P.S.: I'm aware that a Unix timestamp and ticks are not exactly the same thing. They are close enough, though.

By : Tomalak


This video can help you solving your question :)
By: admin