2010-08-04 72 views
3

我使用一些代碼從另一個使用XSLT 2.0減去一個日期:如何將XSLT 2.0日期持續時間轉換爲字符串?

<xsl:template match="moveInDate"> 
    <xsl:value-of select="current-date() - xs:date(.)"/> 
</xsl:template> 

這工作,但它給我留下了P2243D的答案,我假設對應於一個「2243天的時期」(這在數學上是正確的)。

因爲我只需要天數,而不是P和D,我知道我可以使用substring或類似的東西,但作爲XSLT的新手,我很好奇,如果有更好,更優雅的方式要做到這一點比簡單的字符串操作。

回答

7

你可以簡單地使用fn:days-from-duration()得到持續時間爲xs:integer

days-from-duration($arg as xs:duration?)xs:integer?

返回一個xs:integer代表的$arg值的規範詞法表示的日子組件。結果可能是負面的。

有關更多信息,請參閱XQuery 1.0 and XPath 2.0 Functions and Operators規範。

你的情況:

<xsl:template match="moveInDate"> 
    <xsl:value-of select="days-from-duration(current-date() - xs:date(.))"/> 
</xsl:template> 

希望這有助於!

編輯:你也可以按照你說的方式做子串處理。但正如你指出的那樣,這不是首選。如果你由於某種原因想要做類似的事情,你需要考慮數據類型。的current-date() - xs:date(.)結果返回xs:duration不能被串函數來處理,而不被鑄造:

<xsl:template match="moveInDate"> 
    <xsl:variable name="dur" select="(current-date() - xs:date(.)) cast as xs:string"/> 
    <xsl:value-of select="substring-before(substring-after($dur, 'P'), 'D')"/> 
</xsl:template> 
+0

+1好,延長答覆!也用於鏈接規格。 – 2010-08-04 14:16:34

+0

可愛的答案,非常感謝。現在,如果我能弄清楚我的下一個問題:下次如何回答這個問題... – mlissner 2010-08-04 16:16:05

相關問題