Search code examples
datexsltxslt-2.0saxon

How to convert text to date, then get year value?


Need to convert a text value `2012-03-19' into a date type, then extract the year component.

<xsl:variable name="dateValue" select="2012-03-19"/>
<xsl:variable name="year" select="year-from-date(date($dateValue))"/>

I'm using Saxon 2.0, but it's complaining date function does not exist; I looked around Saxon's documentation and could not find the function, so that's clearly the issue, but I can't find a suitable replacement.


Solution

  • I don't think date() should be a function, you want the xs:date() data type.

    Add the xs namespace and then prefix xs:date().

    The following stylesheet, using any well-formed XML input, will produce 2012:

    <xsl:stylesheet version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:template match="/">
        <xsl:variable name="dateValue" select="'2012-03-19'"/>
        <xsl:variable name="year" select="year-from-date(xs:date($dateValue))"/>
        <xsl:value-of select="$year"/>
      </xsl:template>
    
    </xsl:stylesheet>
    

    Note that you also have to quote your select in your "dateValue" xsl:variable.