I have been trying to convert a given dateTime to epoch time and also a given epoch time to dateTime. I am quite new to xslt and have been struggling with this quite for som
To convert Unix time to ISO 8601 date-time:
<xsl:value-of select="xs:dateTime('1970-01-01T00:00:00') + xs:dayTimeDuration(concat('PT', UnixTime, 'S'))"/>
To convert ISO 8601 date-time to Unix time;
<xsl:value-of select="floor((xs:dateTime(ISODateTime) - xs:dateTime('1970-01-01T00:00:00')) div xs:dayTimeDuration('PT1S')) "/>
Requires XSLT 2.0.
Working demo: http://xsltransform.net/94rmq5L
If you are trying to do this in XSLT 1.0 on MSXML (I know the original asker is not):
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ms="urn:schemas-microsoft-com:xslt" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:userCSharp="http://stackoverflow.com/xsltexample">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes" />
<xsl:template match="/">
<xsl:value-of select="userCSharp:DateToEpoch('1970-01-02')" />
</xsl:template>
<msxsl:script language="CSharp" implements-prefix="userCSharp"><![CDATA[
public string DateToEpoch(string s)
{
DateTime dt = DateTime.Parse(s);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return (dt - epoch).TotalSeconds.ToString();
}
]]></msxsl:script>
</xsl:stylesheet>
Replace the '1970-01-02'
with whatever text node you want and this should work, as long as that node was a valid date time. If not, it's easy enough to write up another simple method to do that using DateTime.Parse/TryParse
. The output of this template (against any valid XML) would be 86400
. Note that it's best to define methods in a CDATA
node to avoid needing to escape quotes or angle brackets (this code doesn't happen to use any but might be extended to for some reason).