dateTime到Epoch,反之亦然xslt

时间:2015-10-06 17:16:16

标签: xslt

我一直在尝试将给定的dateTime转换为纪元时间,并将给定的纪元时间转换为dateTime。我对xslt很新,并且已经在这方面苦苦挣扎了一段时间,它没有给我任何结果。这是我到目前为止的xslt

    <xsl:stylesheet version="1.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:ns0="http://www.NoPreAuth.org"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                exclude-result-prefixes="xsi xsl ns0 xsd">
<xsl:template match="/">
<xsl:variable name="date1">
        <xsl:value-of select="/ns0:NoAuthInput/ns0:StartDate"/>
</xsl:variable>
<xsl:variable name="date2">
        <xsl:value-of select="/ns0:NoAuthInput/ns0:EndDate"/>
</xsl:variable>
<ns0:NoPreAuthInput>
<ns0:Product>
        <xsl:value-of select="/ns0:NoAuthInput/ns0:Product"/>
</ns0:Product>
<!-- datTime to epoch -->
<ns0:END_T> 
  <xsl:value-of select= "(('$date1')  - xsd:dateTime('1970-01-01T00:00:00') )  div  xsd:dayTimeDuration('PT1S') "/>
</ns0:END_T>
<!-- epoch To datTime -->
<ns0:Closed_T> 
  <xsl:value-of select= "(('$date2')  + xsd:dateTime('1970-01-01T00:00:00') )  *  xsd:dayTimeDuration('PT1S') "/>
</ns0:Closed_T>
</ns0:NoPreAuthInput>
</xsl:template>
</xsl:stylesheet>

我要转换的xml是:

<?xml version="1.0" encoding="UTF-8" ?>
<NoAuthInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.NoAuth.org 

 xmlns="http://www.NoAuth.org">
   <Product>ABC</Product>
   <StartDate>2015-10-05T15:52:40.782</StartDate>
   <EndDate>1444150760</EndDate>
</NoAuthInput> 

对此非常感谢的任何帮助。谢谢

2 个答案:

答案 0 :(得分:5)

Unix time转换为ISO 8601日期时间:

<xsl:value-of select="xs:dateTime('1970-01-01T00:00:00') + xs:dayTimeDuration(concat('PT', UnixTime, 'S'))"/>

ISO 8601 date-time转换为Unix时间;

<xsl:value-of select="floor((xs:dateTime(ISODateTime) - xs:dateTime('1970-01-01T00:00:00')) div xs:dayTimeDuration('PT1S')) "/>

需要XSLT 2.0。

工作演示:http://xsltransform.net/94rmq5L

答案 1 :(得分:1)

如果您尝试在MSXML上的XSLT 1.0中执行此操作(我知道原始提问者不是):

<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>

'1970-01-02'替换为您想要的任何文本节点,这应该有效,只要该节点是有效的日期时间。如果没有,那么使用DateTime.Parse/TryParse编写另一种简单方法就可以了。此模板的输出(针对任何有效的XML)将为86400。请注意,最好在CDATA节点中定义方法,以避免需要转义引号或尖括号(此代码不会使用任何但可能由于某种原因而扩展)。

相关问题