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

如何在XSL 1.0中从日期获取星期名称?附示例需求

在XSLT 1.0中提取日期对应的星期名称

错误原因

你使用的format-date()是XSLT 2.0及更高版本才支持的函数,XSLT 1.0没有内置该功能,因此会触发解析错误。

解决方案

方案1:使用EXSLT扩展函数(推荐,若处理器支持)

多数XSLT 1.0处理器(如Saxon、Xalan)支持EXSLT的date扩展库,其中date:day-name()可直接获取星期名称。

示例代码:

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:date="http://exslt.org/dates-and-times"
                exclude-result-prefixes="date">

  <xsl:template match="/">
    <ReqdExctnDt>
      <!-- 输出完整星期名称(如Wednesday) -->
      <xsl:value-of select="date:day-name(PaymentDate)" />
      <!-- 要输出缩写(如Wed),截取前3位即可 -->
      <!-- <xsl:value-of select="substring(date:day-name(PaymentDate), 1, 3)" /> -->
    </ReqdExctnDt>
  </xsl:template>

</xsl:stylesheet>

注意:需确保你的XSLT处理器支持EXSLT扩展,并正确声明date命名空间。

方案2:纯XSLT 1.0实现(不依赖扩展)

如果无法使用扩展,可通过Zeller公式计算日期对应的星期数,再映射为星期名称。

示例代码:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/">
    <ReqdExctnDt>
      <xsl:variable name="dateStr" select="PaymentDate" />
      <!-- 拆分YYYY-MM-DD格式的日期为年、月、日 -->
      <xsl:variable name="year" select="substring($dateStr, 1, 4)" />
      <xsl:variable name="month" select="substring($dateStr, 6, 2)" />
      <xsl:variable name="day" select="substring($dateStr, 9, 2)" />
      
      <!-- Zeller公式计算星期:结果h为0=周六,1=周日,2=周一,...,6=周五 -->
      <xsl:variable name="m" select="$month - ($month &lt; 3)" />
      <xsl:variable name="y" select="$year - ($month &lt; 3)" />
      <xsl:variable name="h" select="($day + floor((13 * $m + 3)/5) + $y + floor($y/4) - floor($y/100) + floor($y/400)) mod 7" />
      
      <!-- 映射数字到星期名称 -->
      <xsl:variable name="fullNames" select="'Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday'" />
      <xsl:variable name="shortNames" select="'Sat,Sun,Mon,Tue,Wed,Thu,Fri'" />
      
      <!-- 输出完整名称 -->
      <xsl:value-of select="substring-before(substring-after(concat(',', $fullNames, ','), concat(',', $h+1, ',')), ',')" />
      <!-- 要输出缩写的话,替换成shortNames即可 -->
      <!-- <xsl:value-of select="substring-before(substring-after(concat(',', $shortNames, ','), concat(',', $h+1, ',')), ',')" /> -->
    </ReqdExctnDt>
  </xsl:template>

</xsl:stylesheet>

当PaymentDate输入为2023-09-27时,代码会返回Wednesday(完整名称)或Wed(缩写)。

注意:该实现依赖YYYY-MM-DD的日期格式,若你的日期格式不同,需调整拆分年、月、日的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:36:00