在xslt中将dateTime转换为unix纪元

时间:2010-08-12 12:47:21

标签: datetime xslt xpath xslt-2.0 xpath-2.0

我有一个dateTime变量,我想将其转换为纪元的十进制值。 怎么办呢?

我尝试使用:

seconds-from-duration($time, xs:dateTime('1970-01-01T00:00:00'))

但它只返回0.

请指教。 感谢。

3 个答案:

答案 0 :(得分:14)

此转化

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output method="text"/>

 <xsl:template match="/">
   <xsl:sequence select="current-dateTime()"/>

   <xsl:sequence select=
   "( current-dateTime() - xs:dateTime('1970-01-01T00:00:00') )
    div
     xs:dayTimeDuration('PT1S')
     "/>
 </xsl:template>
</xsl:stylesheet>

应用于任何XML文档(未使用)时,产生想要的结果 - 当前日期时间及其Unix纪元(自1970年1月1日以来的秒数):< / p>

2010-08-12T06:26:54.273-07:00    1281594414.273

答案 1 :(得分:4)

一个pure xsl 1.0 lib示例:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:date="https://github.com/ilyakharlamov/pure-xsl/date"
    version="1.0">
    <xsl:import href="https://raw.github.com/ilyakharlamov/pure-xsl/master/date.xsl"/>
    <xsl:template match="/">
        <xsl:variable name="time_as_timestamp" select="1365599995640"/>
        <xsl:text>time_as_timestamp:</xsl:text><xsl:value-of select="$time_as_timestamp"/><xsl:text>&#x0A;</xsl:text>
        <xsl:variable name="time_as_xsdatetime">
            <xsl:call-template name="date:date-time">
                <xsl:with-param name="timestamp" select="$time_as_timestamp"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:text>time_as_xsdatetime:</xsl:text><xsl:value-of select="$time_as_xsdatetime"/><xsl:text>&#x0A;</xsl:text>
        <xsl:text>converted back:</xsl:text>
        <xsl:call-template name="date:timestamp">
            <xsl:with-param name="date-time" select="$time_as_xsdatetime"/>
        </xsl:call-template>
    </xsl:template>
</xsl:stylesheet>

输出:

time_as_timestamp:1365599995640个
time_as_xsdatetime:2013-04-10T13:19:55.640Z
转换回来:1365599995640

答案 2 :(得分:0)

作为不使用除法的xpath,但是从持续时间中提取:

for $i in (current-dateTime()-xs:dateTime('1970-01-01T00:00:00Z')) 
    return ((days-from-duration($i)*86400)+(hours-from-duration($i)*3600)+(minutes-from-duration($i)*60)+(seconds-from-duration($i)))