Nibble

XSLT formatting dates

Recently I needed to get a date in this format : April 19th 2008

Getting a format like ‘April 19 2008′ is easy, you can just use the umbraco library method FormatDateTime. But to get to the ‘April 19th 2008′ format I needed to write a some extra xslt.

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE xsl:Stylesheet [ &lt;!ENTITY nbsp “&#x00A0;”> ]>
<xsl:stylesheet
version=”1.0″
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
xmlns:msxml=”urn:schemas-microsoft-com:xslt”
xmlns:umbraco.library=”urn:umbraco.library”
exclude-result-prefixes=”msxml umbraco.library”>
 
 
<xsl:output method=”xml” omit-xml-declaration=”yes”/>
 
<xsl:param name=”currentPage”/>
 
<xsl:template match=”/”>
 
<!– The fun starts here –>
 
<xsl:for-each select=”$currentPage/node [string(data [@alias=’umbracoNaviHide’]) != ‘1′]”>
<xsl:variable name=”day” select=”substring(@createDate,9,2)” />
 
<xsl:choose>
<xsl:when test=”$day = ‘01′ or $day = ‘21′”>
<xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’MMMM d’)”/>st <xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’yyyy’)”/>
 
</xsl:when>
<xsl:when test=”$day = ‘02′ or $day = ‘22′”>
<xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’MMMM d’)”/>nd <xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’yyyy’)”/>
 
</xsl:when>
<xsl:when test=”$day = ‘03′ or $day = ‘23′”>
<xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’MMMM d’)”/>rd <xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’yyyy’)”/>
 
</xsl:when>
<xsl:otherwise>
<xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’MMMM d’)”/>th <xsl:value-of select=”umbraco.library:FormatDateTime(@createDate,’yyyy’)”/>
</xsl:otherwise>
</xsl:choose>
 
</xsl:for-each>
 
 
</xsl:template>
 
</xsl:stylesheet>

First I created a variable day that retrieves the day out of the createdate and then depending on wich day it is I add ’st’, ‘nd’, ‘rd’ or ‘th’.

3 Comments so far

  1. Keith Chadwick on June 12th, 2008

    I was looking at your date code and it occurred to me that the below would be even easier and a lot smaller, assuming $dte holds the date. Also you did not account for the 31st in your code

  2. Keith Chadwick on June 13th, 2008

    Think your parser stripped out the xsl I pasted, so I will do it again with the encoded characters:

    <xsl:variable name=”dte” select=”@createDate”/>
    <xsl:variable name=”endings” select=”umbraco.library:Split(’st,nd,rd,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,th,st,nd,rd,th,th,th,th,th,th,th,st’,',’)”/>
    <xsl:value-of select=”concat(umbraco.library:FormatDateTime($dte,’MMMM d’),$endings/value[number(substring($dte,9,2))]/text(),’ ‘,substring($dte,1,4))”/>

  3. Tim Geyssens on June 13th, 2008

    Great job Keith !

Leave a Reply