首页 > 解决方案 > XSLT 2.0 重新格式化日期

问题描述

假设我有一个以“2018-03-00”形式编写的日期。我希望这是“00-MAR-18”。XSLT 2.0 中的哪些功能(如果有)可用于此。

我正在寻找月份(3)= MAR。我打算自己编写附加字段。

标签: xsltxslt-2.0

解决方案


看看format-date()

日期为“00”时,您的日期不能转换为 xs:date。如果你真的有“00”,你将无法使用format-date().

如果您的日期可转换为 xs:date's,这里有一个例子......

XML 输入

<test>2018-03-01</test>

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">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:value-of select="format-date(., '[D01]-[MN,*-3]-[Y01]')"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

输出

<test>01-MAR-18</test>

小提琴:http: //xsltfiddle.liberty-development.net/3NzcBtj

编辑

由于您的日期不是真正的日期,您可以创建自己的函数......

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:so="stackoverflow.test">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:function name="so:format_month">
    <xsl:param name="date_string"/>
    <xsl:variable name="months" select="(
      'JAN','FEB','MAR',
      'APR','MAY','JUN',
      'JUL','AUG','SEP',
      'OCT','NOV','DEC')"/>
    <xsl:variable name="date_tokens" select="tokenize($date_string,'-')"/>
    <xsl:value-of select="($date_tokens[3],
      $months[number($date_tokens[2])],
      substring($date_tokens[1],3,2))" separator="-"/>
  </xsl:function>

  <xsl:template match="/*">
    <xsl:copy>
      <xsl:value-of select="so:format_month(.)"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

小提琴:http: //xsltfiddle.liberty-development.net/3NzcBtj/2


推荐阅读