在 XSLT 2.0 中是否有一个函数可以从 2 个日期计算持续时间?
我正在尝试根据出生日期和当前日期计算以下内容:
- 年龄
- 月龄
最佳答案
我不知道 XSLT 中有一个预定义的函数来完成这个。但是您始终可以编写自己的代码。下面的解决方案不使用函数,但您可以轻松地将其重写为函数。
计算思路来自here .
还有其他(更短的)方法可以解决这个问题,有关 XSLT 2.0 特定的解决方案,请参阅 Mads Hansen 的回答 here , 例如。不过,您必须稍微调整您在那里找到的样式表,因为它会输出天数。
输入
<root>
<birth>1964-10-10</birth>
</root>
样式表
<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" />
<xsl:variable name="Birthday" select="//birth[1]"/>
<xsl:variable name="Age">
<xsl:choose>
<xsl:when test="month-from-date(current-date()) > month-from-date($Birthday) or month-from-date(current-date()) = month-from-date($Birthday) and day-from-date(current-date()) >= day-from-date($Birthday)">
<xsl:value-of select="year-from-date(current-date()) - year-from-date($Birthday)" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="year-from-date(current-date()) - year-from-date($Birthday) - 1" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:template match="/root">
<result>
<xsl:value-of select="$Age"/>
</result>
</xsl:template>
</xsl:stylesheet>
输出
<?xml version="1.0" encoding="UTF-8"?><result>49</result>
关于date - XSLT 2.0 : Calculate age from DOB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22148777/