Parsing Dates in XSLT

By Andu Wu

There is no built in support in XSLT for parsing dates. Given the many formats a date can come in, it makes for an interesting problem.

One solution, when faced with a known format of date, is to use the substring functions to workaround this lack of functionality.

Given the date in the following format "Fri, 4 Mar 2005 10:50:35", it's possible to create a template to extract the individual parts of the date and format it as you wish.

<xsl:template name="format-date">
  <xsl:param name="date" />

  <xsl:variable name="day" 
    select="substring-before(substring-after($date, ' '), ' ')" />
  <xsl:variable name="monthName" 
    select="substring-before(substring-after(substring-after($date, ' '), ' '), ' ')" />
  <xsl:variable name="year" 
    select="substring-before(substring-after(substring-after(
      substring-after($date, ' '), ' '), ' '), ' ')" />
  <xsl:variable name="time" 
    select="substring-before(substring-after(
      substring-after(substring-after(substring-after($date, ' '), ' '), ' '), ' '), ' ')" />

  <!-- convert the month to a numeric -->
  <xsl:variable name="month" 
    select="substring(
      substring-after('Jan01Feb02Mar03Apr04May05Jun06Jul07Aug08Sep09Oct10Nov11Dec12',
      $monthName), 1, 2)" />

  <!-- remove the leading 0 (you could skip these steps) -->
  <xsl:variable name="day2" 
    select="concat(translate(substring($day,1,1), '0', ''), 
      substring($day,2,1))" />
  <xsl:variable name="month2" 
    select="concat(translate(substring($month,1,1), '0', ''), 
      substring($month,2,1))" />

  <!-- create the date in the new format -->
  <xsl:value-of select="concat( $year, '-', $month2, '-', $day2, ' ', $time )" />

</xsl:template>

Most Recent

Most Popular

Most Active Categories




Back To Top Add New Article Printable Page
MediaWiki

This page has been accessed 3,304 times.

This page was last modified 16:24, 27 April 2006.