How to parse string to date in xslt 2.0

VextoR picture VextoR · May 31, 2013 · Viewed 31.6k times · Source

Is it possible to convert strings like 30042013 (30 April 2013) to a date format?

So I can use it later in functions like format-date

Answer

Daniel Haley picture Daniel Haley · May 31, 2013

Like Tomalak said, you can use substring() and concat() to build a string you can cast as an xs:date() (It doesn't sound like you want a dateTime.)

Example:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:variable name="in" select="'30042013'"/>

    <xsl:template match="/">
        <xsl:variable name="date" select="xs:date(concat(
            substring($in,5,4),'-',
            substring($in,3,2),'-',
            substring($in,1,2)))"/>
        <xsl:value-of select="format-date($date,'[MNn] [D], [Y]')"/>
    </xsl:template>

</xsl:stylesheet>

produces (with any XML input)

April 30, 2013