date - XSLT 2.0 : Calculate age from DOB

标签 date xslt duration

在 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/

相关文章:

javascript - 日期格式被错误解释

jQuery removeClass 持续时间不起作用?

MySQL : first day of the week and last day of the week not working as desired

date - 显示自给定日期以来的修改(新文件和编辑文件)

c# - LINQ - Group List<T> 到年、月、日

xslt - 如何打印作为文本一部分的 < 和 > 符号..?

xml - XSL 在 for-each 中按属性查找元素

linux - Bash - 日期命令和空格

FFMPEG:如何正确地为我的视频添加文本覆盖并将其保存为缩略图?

c++ boost计算函数花费的时间