3

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

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

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

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

4

1 回答 1

7

您可以简单地使用fn:days-from-duration()来获取持续时间xs:integer

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

在 的值的规范词法表示中返回一个xs:integer表示天分量的值$arg。结果可能是否定的。

有关更多信息,请参阅XQuery 1.0 和 XPath 2.0 函数和运算符规范。

在你的情况下:

<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>
于 2010-08-04T07:14:40.693 回答