Print

Formatting a date in XSLT is a pain, so the more examples their are online the better i think.

I was required to convert a date in a US format mm/dd/yy hh:min AM/PM to the xml standard YYYY-MM-DDTHH24:MIN:SS

I started of using the tamplate found at the bottom of http://stackoverflow.com/questions/16484193/convert-date-from-dd-mmm-yyyy-to-yyyymmdd-format-in-xslt-1-0 and altered it match my needs.

The original template did not handle checking for AM/PM and the year represented as yy.

<xsl:template name="date">
<xsl:param name="slashFormattedDate"/>
<xsl:param name="hasTime"/>
<xsl:variable name="dd"
select="format-number(substring-before($slashFormattedDate, '/'),'00')"/>
<xsl:variable name="monthYear"
select="substring-after($slashFormattedDate, '/')"/>
<xsl:variable name="mm" select="format-number(substring-before($monthYear, '/'),'00')"/>
<xsl:variable name="yyyyTemp1" select="substring-after($monthYear, '/')"/>
<xsl:variable name="yyyyTemp2">
<xsl:choose>
<xsl:when test="$hasTime='Y'">
<xsl:value-of select="substring-before($yyyyTemp1, ' ')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$yyyyTemp1"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="yyyy">
<xsl:choose>
<xsl:when test="string-length($yyyyTemp2) = 2 and $yyyyTemp2 > 50">
<xsl:value-of select="concat('19',$yyyyTemp2)"/>
</xsl:when>
<xsl:when test="string-length($yyyyTemp2) = 2 and $yyyyTemp2 &lt;= 50">
<xsl:value-of select="concat('20',$yyyyTemp2)"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$yyyyTemp2"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="timeTemp">
<xsl:choose>
<xsl:when test="$hasTime='Y'">
<xsl:value-of select="substring-after($yyyyTemp1, ' ')"/>
</xsl:when>
</xsl:choose>
</xsl:variable>
<xsl:variable name="time">
<xsl:choose>
<xsl:when test="substring-after($timeTemp, ' ') = 'PM' and number(substring-before($timeTemp, ':')) &lt; 12">
<xsl:value-of select="concat(number(substring-before($timeTemp, ':'))+12,':',substring-after(substring-before($timeTemp,' '), ':'),':00')"/>
</xsl:when>
<xsl:when test="contains($timeTemp,' ')">
<xsl:value-of select="concat(format-number(substring-before($timeTemp, ':'),'00'),':',substring-after(substring-before($timeTemp,' '), ':'),':00')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat(format-number(substring-before($timeTemp, ':'),'00'),':',substring-after($timeTemp,':'),':00')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:choose>
<xsl:when test="$hasTime='Y'"><xsl:value-of select="$yyyy" disable-output-escaping="yes"/>-<xsl:value-of select="$mm" disable-output-escaping="yes"/>-<xsl:value-of select="$dd" disable-output-escaping="yes"/>T<xsl:value-of select="$time" disable-output-escaping="yes"/></xsl:when>
<xsl:otherwise><xsl:value-of select="$yyyy" disable-output-escaping="yes"/>-<xsl:value-of select="$mm" disable-output-escaping="yes"/>-<xsl:value-of select="$dd" disable-output-escaping="yes"/></xsl:otherwise>
</xsl:choose>
</xsl:template>