Page 1 of 1
XSL Help formating dates
Posted: Fri Sep 26, 2008 11:27 am
by danmat46
This is probably the worse thing I have ever attempted in xsl
formating a date value that can be any of the following:
MM/DD/YY
M/DD/YY
M/D/YY
MM/D/YY
changing it into YY-MM-DD
Any guidance?
Re: XSL Help formating dates
Posted: Fri Sep 26, 2008 5:37 pm
by george
Hi,
Let's suppose you have
Code: Select all
<dates>
<date>11/12/03</date>
<date>1/12/03</date>
<date>1/2/03</date>
<date>11/2/03</date>
</dates>
and you want as output
Code: Select all
<dates>
<date>03-11-12</date>
<date>03-01-12</date>
<date>03-01-02</date>
<date>03-11-02</date>
</dates>
Then, the following stylesheet will do that. It gets the year, month and day with substring before and after functions and then adds a leading zero if necessary:
Code: Select all
<?xml version="1.1" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match="dates">
<dates><xsl:apply-templates/></dates>
</xsl:template>
<xsl:template match="date">
<xsl:variable name="year" select="substring-after(substring-after(., '/'),'/')"/>
<xsl:variable name="month" select="substring-before(.,'/')"/>
<xsl:variable name="day" select="substring-before(substring-after(., '/'),'/')"/>
<date>
<xsl:value-of select="$year"/>
<xsl:text>-</xsl:text>
<xsl:if test="string-length($month)=1">0</xsl:if>
<xsl:value-of select="$month"/>
<xsl:text>-</xsl:text>
<xsl:if test="string-length($day)=1">0</xsl:if>
<xsl:value-of select="$day"/>
</date>
</xsl:template>
</xsl:stylesheet>
Best Regards,
George