Format a date in XML via XSLT


When I use the XML serializer to serialize a DateTime, it is written in the following format:


When passing this through an XSLT stylesheet to output HTML, how can I format this? In most cases I just need the date, and when I need the time I of course don't want the "funny T" in there.

4/14/2013 2:52:41 PM

Accepted Answer

Here are a couple of 1.0 templates that you can use:-

<xsl:template name="formatDate">
    <xsl:param name="dateTime" />
    <xsl:variable name="date" select="substring-before($dateTime, 'T')" />
    <xsl:variable name="year" select="substring-before($date, '-')" />
    <xsl:variable name="month" select="substring-before(substring-after($date, '-'), '-')" />
    <xsl:variable name="day" select="substring-after(substring-after($date, '-'), '-')" />
    <xsl:value-of select="concat($day, ' ', $month, ' ', $year)" />

<xsl:template name="formatTime">
    <xsl:param name="dateTime" />
    <xsl:value-of select="substring-after($dateTime, 'T')" />

Call them with:-

    <xsl:call-template name="formatDate">
        <xsl:with-param name="dateTime" select="xpath" />


    <xsl:call-template name="formatTime">
        <xsl:with-param name="dateTime" select="xpath" />

where xpath is the path to an element or attribute that has the standard date time format.

2/1/2009 3:01:35 PM

Date formatting is not easy in XSLT 1.0. Probably the most elegant way is to write a short XSLT extension function in C# for date formatting. Here's an example:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="" version="1.0"
                exclude-result-prefixes="msxsl myExtension">
  <xsl:output method="xml" indent="yes"/>

  <msxsl:script implements-prefix="myExtension" language="C#">
      public string FormatDateTime(string xsdDateTime, string format)
          DateTime date = DateTime.Parse(xsdDateTime);
          return date.ToString(format); 


  <xsl:template match="date">
      <xsl:value-of select="myExtension:FormatDateTime(self::node(), 'd')"/>

With this input document

<?xml version="1.0" encoding="utf-8"?>

you will get

<?xml version="1.0" encoding="utf-8"?>

The function formatting the date takes a date value as string and a format as described in DateTime.ToString Method. Using .NET's DateTime struct gives you parsing arbitrary XSD datetime values (including time zone specifiers), timezone calculation and localized output for free.

However, be aware that there is one caveat ( with msxml script extensions: Each time you load the XSLT an assembly containing the script code is generated dynamically and loaded into memory. Due to the design of the .NET runtime, this assembly cannot be unloaded. That's why you have to make sure that your XSLT is only loaded once (and then cached for further re-use). This is especially important when running inside IIS.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow