【问题标题】:How do you convert an XSLT 2.0 date duration to a string?如何将 XSLT 2.0 日期持续时间转换为字符串?
【发布时间】:2010-08-04 06:55:09
【问题描述】:

我正在使用一些代码使用 XSLT 2.0 从另一个日期中减去一个日期:

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

这可行,但它给我留下了 P2243D 的答案,我认为它对应于 “2243 天的时期”(在数学方面是正确的)。

由于我只需要天数,而不是 P 和 D,我知道我可以使用 substring 或类似的东西,但作为 XSLT 的新手,我很好奇是否有更好、更优雅的方法这样做比简单的字符串操作。

【问题讨论】:

    标签: math xslt date duration


    【解决方案1】:

    您可以简单地使用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>
    

    【讨论】:

    • 可爱的答案,非常感谢。现在,如果我能弄清楚我的下一个问题:下次如何自己回答这个问题......
    猜你喜欢
    • 2020-10-21
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多