问题
I am new to xslt. so this might be a basic question. I am trying to convert a date received in xs:date format to DD-MON-YYYY
input received is :
<tns:receivedDate>2017-06-27</tns:receivedDate>
Output expected
<tns:receivedDate>27-JUN-2017</tns:receivedDate>
Thanks in advance
回答1:
If you mean convert YYYY-MM-DD
to DD-MMM-YYYY
, try:
<xsl:template name="format-date">
<xsl:param name="date"/>
<!-- day -->
<xsl:value-of select="substring($date, 9, 2)"/>
<xsl:text>-</xsl:text>
<!-- month -->
<xsl:variable name="m" select="substring($date, 6, 2)"/>
<xsl:value-of select="substring('JanFebMarAprMayJunJulAugSepOctNovDec', 3*($m - 1)+1, 3)"/>
<xsl:text>-</xsl:text>
<!-- year -->
<xsl:value-of select="substring($date, 1, 4)"/>
</xsl:template>
Demo: https://xsltfiddle.liberty-development.net/94rmq7k
回答2:
In XSLT-1.0 you have to implement the transformation yourself - without the help of build-in functions.
So a solution could look like the following. It uses a data-island in the XSLT to map the month's names. I defined the tns
namespace to be http://towelie.namespace
.
The sample XML:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:tns="http://towelie.namespace">
<tns:receivedDate>2017-06-27</tns:receivedDate>
</root>
The solution XSLT-1.0 stylesheet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://towelie.namespace" xmlns:month="http://month.val" version="1.0">
<xsl:output method="text" />
<!-- Data island -->
<month:val>
<mon>JAN</mon>
<mon>FEB</mon>
<mon>MAR</mon>
<mon>APR</mon>
<mon>MAI</mon>
<mon>JUN</mon>
<mon>JUL</mon>
<mon>AUG</mon>
<mon>SEP</mon>
<mon>OCT</mon>
<mon>NOV</mon>
<mon>DEC</mon>
</month:val>
<xsl:template match="/root">
<xsl:apply-templates select="tns:receivedDate" />
</xsl:template>
<xsl:template match="tns:receivedDate">
<xsl:variable name="year" select="substring-before(.,'-')" />
<xsl:variable name="month" select="substring-before(substring-after(.,'-'),'-')" />
<xsl:variable name="day" select="substring-after(substring-after(.,'-'),'-')" />
<xsl:value-of select="concat($day,'-',document('')/xsl:stylesheet/month:val/mon[number($month)]/text(),'-',$year)" />
</xsl:template>
</xsl:stylesheet>
In this stylesheet the input date is dissected to three variables which are then recombined in the xsl:value-of
applying an index to the data-island's mon
elements.
The output:
27-JUN-2017
Final comment:
An important advantage of this approach is that you can define the month's names as you like - with different lengths in different languages - i.e. JAN, Jan, January, Janvier, Januar, Enero, ...
And the data-island could be replaced by external XML files. For example, one for each language.
来源:https://stackoverflow.com/questions/57615867/xslt-1-0-to-convert-xsdate-to-a-specific-dateformat-dd-mon-yyyy