math - 如何将 XSLT 2.0 日期持续时间转换为字符串?

标签 math xslt date duration

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

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

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

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

最佳答案

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

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

Returns an xs:integer representing the days component in the canonical lexical representation of the value of $arg. The result may be negative.

参见 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>

关于math - 如何将 XSLT 2.0 日期持续时间转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3403248/

相关文章:

Java程序以10^-6精度确定嵌套根式常量的值

c++ - 在 C/C++ 中实现导数

c# - 如何在 C# 中正确地多次分割/除一个整数?

xslt - 使用xslt获取X位置的节点值

php - MySQL:统计A月到B月的数据

sql - 在sql中的某个日期之前获取值

c++ - C++ 中的 "Summable Numbers"

xml - XSL 转换后的空标签

r - 如何在 R 中转换 Redis 日期

internet-explorer - 使用 XSLT 创建条件注释?