我想计算XSLT2.0中两个日期之间的年差。我试过:
xs:dayTimeDuration(xs:date('2007-03-02')-xs:date('2002-03-01'))给我不同的日子:
P1827D帮助实现的是一个函数,它以两个日期之间的几年、几个月和几天来计算一个“规范化”的xs:duration,比如本例中的P1Y0M1D,我可以从中提取出年份P1Y。从仅由天组成的xs:duration中提取一年是不可能的(而且也没有多大意义)。
那么,如何计算两个日期之间的年差,而不是以天为单位?
发布于 2022-03-17 18:56:28
我猜(!)您希望返回一个与整个年份中表示的年龄相等的结果,使用的习惯规则是,在每个生日时,年龄增加一岁。这可以使用以下模板(可以转换为函数)来计算:
<xsl:template name="age-in-years">
<xsl:param name="start-date"/>
<xsl:param name="end-date"/>
<xsl:variable name="start-year" select="year-from-date($start-date)"/>
<xsl:variable name="start-month" select="month-from-date($start-date)"/>
<xsl:variable name="start-day" select="day-from-date($start-date)"/>
<xsl:variable name="end-year" select="year-from-date($end-date)"/>
<xsl:variable name="end-month" select="month-from-date($end-date)"/>
<xsl:variable name="end-day" select="day-from-date($end-date)"/>
<xsl:value-of select="$end-year - $start-year - number(100 * $end-month + $end-day lt 100 * $start-month + $start-day)" />
</xsl:template> 请注意,这假设2月29日出生的人的生日发生在非闰年的3月1日。
发布于 2022-03-18 09:04:50
我自己想出了一个递归的解决方案。它不是最具表现力的,但它起作用了:
<xsl:function name="d:years-diff">
<xsl:param name="old.date" as="xs:date"/>
<xsl:param name="new.date" as="xs:date"/>
<xsl:variable name="one-year" select="xs:yearMonthDuration('P1Y')"/>
<xsl:choose>
<xsl:when test="$old.date + $one-year <= $new.date">
<xsl:sequence select="$one-year + d:years-diff($old.date + $one-year, $new.date)"/>
</xsl:when>
<xsl:otherwise>
<xsl:sequence select="xs:yearMonthDuration('P0Y')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>可以使用以下代码验证该函数:
<xsl:template match="/">
<xsl:text>
One day short of five years:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2002-03-02'), xs:date('2007-03-01'))"/>
<xsl:text>
Exactly 5 years:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2002-03-02'), xs:date('2007-03-02'))"/>
<xsl:text>
One day short of one year:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2007-03-02'), xs:date('2006-03-01'))"/>
<xsl:text>
Exactly one year:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2006-03-02'), xs:date('2007-03-02'))"/>
<xsl:text>
One year plus one day:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2006-03-02'), xs:date('2007-03-03'))"/>
<xsl:text>
Same dates:
</xsl:text>
<xsl:value-of select="d:years-diff(xs:date('2007-03-03'), xs:date('2007-03-03'))"/>
</xsl:template>打印出来:
One day short of five years:
P4Y
Exactly 5 years:
P5Y
One day short of one year:
P0M
Exactly one year:
P1Y
One year plus one day:
P1Y
Same dates:
P0Mhttps://stackoverflow.com/questions/71515910
复制相似问题