2010-08-12 48 views
10

我有一個dateTime變量,我想將其轉換爲時代的十進制值。 這怎麼辦?將日期時間轉換爲xslt中的unix時代

我試着使用:

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

,但它只是返回0

請指點。 謝謝。

+0

如何定義「新紀元」? – 2010-08-12 13:04:13

+0

你的問題的答案是:'0'。 seconds-from-duration()只是從提供的xs:duration中提取秒分量的值。你顯然希望將持續時間轉換爲所有秒,然後計算任何「時代」可能。請糾正你的問題。 – 2010-08-12 13:10:24

+0

有關時代的定義,請參閱以下內容:http://en.wikipedia.org/wiki/Unix_time。基本上,這是自1970年1月1日以來的秒數(UTC) – Anna 2010-08-12 13:12:02

回答

13

該轉化

<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時間戳(自1的秒數/ 1/1970)

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

這太棒了!像魔術一樣工作。非常感謝。 – Anna 2010-08-12 13:50:58

+1

+1除以xs:持續時間(我正在提取每個組件,所以我刪除了答案)。但是我一直在想如果**時區**是爲* nix時代定義的。 – 2010-08-12 13:51:11

+1

+1清晰簡潔的答案。非常整齊。 – tatlar 2011-10-12 22:15:21

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

+0

考慮到LibXML2 _still_不支持XPath 2.0函數 - 在* 20-freaking-15 *中 - 這個答案很棒,完全爲我節省了一大堆時間。謝謝! – aendrew 2015-11-11 17:51:12

相關問題