You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT 1.0中基于EDT格式日期计算1年前结果并转指定格式

XSLT 1.0 日期减1年转换方案

XSLT 1.0 没有原生的日期运算函数,我们通过字符串解析、数值计算加闰年边界处理实现需求,完整模板如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- 闰年判断模板:返回1是闰年,0不是 -->
    <xsl:template name="is-leap-year">
        <xsl:param name="year"/>
        <xsl:choose>
            <xsl:when test="($year mod 4 = 0 and $year mod 100 != 0) or ($year mod 400 = 0)">1</xsl:when>
            <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
    </xsl:template>

    <!-- 核心转换模板:传入日期字符串(yyyy-MM-dd)、时间字符串(HH:mm:ss 时区) -->
    <xsl:template name="subtract-one-year">
        <xsl:param name="input-date"/>
        <xsl:param name="input-time"/>

        <!-- 拆分日期字段 -->
        <xsl:variable name="orig-year" select="substring($input-date, 1, 4)"/>
        <xsl:variable name="orig-month" select="substring($input-date, 6, 2)"/>
        <xsl:variable name="orig-day" select="substring($input-date, 9, 2)"/>
        <!-- 拆分时间字段 -->
        <xsl:variable name="hour" select="substring($input-time, 1, 2)"/>
        <xsl:variable name="minute" select="substring($input-time, 4, 2)"/>
        <xsl:variable name="second" select="substring($input-time, 7, 2)"/>
        <xsl:variable name="timezone" select="substring-after($input-time, ' ')"/>

        <xsl:variable name="new-year" select="$orig-year - 1"/>
        <!-- 处理闰年2月29日特殊场景 -->
        <xsl:variable name="is-orig-leap">
            <xsl:call-template name="is-leap-year">
                <xsl:with-param name="year" select="$orig-year"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="new-day">
            <xsl:choose>
                <xsl:when test="$is-orig-leap = 1 and $orig-month = '02' and $orig-day = '29'">28</xsl:when>
                <xsl:otherwise><xsl:value-of select="$orig-day"/></xsl:otherwise>
            </xsl:choose>
        </xsl:variable>

        <!-- 按要求输出,如需HTML加粗年份,替换为<strong><xsl:value-of select="$new-year"/></strong> -->
        <xsl:value-of select="concat($new-year, $orig-month, $new-day, $hour, $minute, $second, ' ', $timezone)"/>
    </xsl:template>

    <!-- 测试调用示例 -->
    <xsl:template match="/">
        <xsl:call-template name="subtract-one-year">
            <xsl:with-param name="input-date" select="'2021-09-21'"/>
            <xsl:with-param name="input-time" select="'11:14:20 EDT'"/>
        </xsl:call-template>
    </xsl:template>
</xsl:stylesheet>

说明

  • 如果需要输出HTML格式的加粗年份,把输出部分的$new-year包裹在<strong>标签中即可,针对你给出的输入示例会输出<strong>2020</strong>0921111420 EDT
  • 已经覆盖闰年边界场景:例如输入2024-02-29 12:00:00 EDT,会自动输出20230228120000 EDT
  • 如果你需要处理动态的当前日期时间,可将当前日期时间作为参数传入模板调用,纯标准XSLT 1.0没有获取当前时间的内置函数,需依赖处理器扩展或外部传参。

内容的提问来源于stack exchange,提问作者Virat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:48:03