在 XSLT 1.0 中,没有将日期转换为特定格式的函数(如 @michael.hor257k 所说)。
您可以根据自己的环境具体通过以下两种方式实现:
1. 如果您使用的是 java,您可以使用 java.util.TimeZone 和 java.util.Calendar API 编写 Util 类.
在 util 类中定义最终静态常量,并使用这些 API 将值解析为所需的日期格式。
2.假设您有如下输入源:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root>
<nightlyRate date="20180312" />
</Root>
然后 xslt 对其进行转换将使用简单的substring() 函数:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output indent="yes" />
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<date>
<xsl:call-template name="getFormattedDate">
<xsl:with-param name="date" select="Root/nightlyRate/@date" />
</xsl:call-template>
</date>
</xsl:template>
<xsl:template name="getFormattedDate">
<xsl:param name="date" />
<xsl:value-of select="concat(substring($date,1,4),'/',substring($date,5,2),'/',substring($date,7,2))" />
</xsl:template>
在 XSLT 2.0 中,
取同一个输入源,可以写成:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"
version="2.0">
<xsl:output omit-xml-declaration="yes" />
<xsl:template match="/">
<xsl:variable name="dateString">
<xsl:value-of select="substring(Root/nightlyRate/@date,1,4)" />
<xsl:text>-</xsl:text>
<xsl:value-of select="substring(Root/nightlyRate/@date,5,2)" />
<xsl:text>-</xsl:text>
<xsl:value-of select="substring(Root/nightlyRate/@date,7,2)" />
</xsl:variable>
<RequiredFormat>
<xsl:value-of select="format-date(xs:date($dateString), '[Y]/[M]/[D]')" />
</RequiredFormat>
<OtherFormat>
<xsl:value-of select="format-date(xs:date($dateString), '[MNn] [D], [Y]')" />
</OtherFormat>
</xsl:template>
输出将是:
<RequiredFormat>2018/3/12</RequiredFormat>
<OtherFormat>March 12, 2018</OtherFormat>