将周数日期 YY-WW-DW 转换为标准的 xslt 日期格式 YYYY-MM-DD

Convert week number date YY-WW-DW into standard xslt date format YYYY-MM-DD

如何使用 xslt 3 将周日期 YYWWWD(其中 YY - 年,WW - 周数和 WD - 星期 1-7)转换为 ISO 8601 的标准格式 YYYY-MM-DD。

示例:21133 年份:21 周数:13 工作日:3(星期三) 转换为 2021-03-31

输入:

<Line>
    <week>2113</week>
    <day>3</day>
</Line>

输出:

<Line>
    <Date>2021-03-31</Date>
</Line>

我尝试了计算规则,但在元旦前后的日期逻辑上遇到了困难,例如将 20537 转换为 2021-01-03 的情况。

这是您可以用作起点的示例。它将 ISO week date 格式的日期转换为标准的 YYYY-MM-DD 日期格式:

XML

<input>
    <ISO-week-date>2006-W02-7</ISO-week-date>
    <ISO-week-date>2021-W13-3</ISO-week-date>
    <ISO-week-date>2020-W53-7</ISO-week-date>
</input>

XSLT 2.0

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/input">
    <output>
        <xsl:for-each select="ISO-week-date">
            <!-- extract ISO-week-date components -->
            <xsl:variable name="year" select="substring(., 1, 4)"/>
            <xsl:variable name="week" select="xs:integer(substring(., 7, 2))"/>
            <xsl:variable name="weekday" select="xs:integer(substring(., 10, 1))"/>
            <!-- calculate base Sunday  -->
            <xsl:variable name="base" select="xs:date(concat($year, '-01-04'))"/>
            <xsl:variable name="base-weekday" select="xs:integer(format-date($base, '[F1]'))"/>
            <xsl:variable name="base-sunday" select="$base - $base-weekday * xs:dayTimeDuration('P1D')"/>
            <!-- calculate standard date  -->
            <xsl:variable name="target-date" select="$base-sunday + ($week - 1) * xs:dayTimeDuration('P7D') + $weekday * xs:dayTimeDuration('P1D')"/>
            <date>
                <xsl:value-of select="$target-date"/>
            </date>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

结果

<?xml version="1.0" encoding="utf-8"?>
<output>
   <date>2006-01-15</date>
   <date>2021-03-31</date>
   <date>2021-01-03</date>
</output>

如果您的周数遵循与 ISO 8601 日期和时间标准相同的约定,那么您只需调整提取输入组件的部分。

当然,如果你不止一个地方需要这个,你可以把它变成一个函数。