Search code examples
javascriptxsltxslt-extension

XSLT Javascript extension can not call Date().toISOString()


I have been experimenting with using extensions in Microsoft XSLT (1.0). In the JavaScript function I am just trying to return the current ISO date and time. Sounds easy enough.

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                           xmlns:ms="urn:schemas-microsoft-com:xslt"
                           xmlns:util="urn:Utility" extension-element-prefixes="ms"
                            >
    <xsl:output method="html" version="1.0"/>
    <ms:script language="javascript" implements-prefix="util">
    function today()
    {
        var d = new Date();
        return d.toISOString();
    }
    </ms:script>
    <!-- =============================================================== -->
    <xsl:template match="Person">
       <xsl:value-of select="util:today()"/>
    </xsl:template>
    </xsl:stylesheet>

When you execute the above it returns "Function expected". According to the Microsoft documentation toISOString is supposed for the JavaScript Date() object. If I use toGMTString() it returns the GMT value. I really need the current date returned in ISO format.

Any ideas?


Solution

  • toISOString() is not a property of the original jScript Date object.

    It is supported in IE9+, and even there in standards rendering mode only.

    Try this.

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:ms="urn:schemas-microsoft-com:xslt"
      xmlns:util="urn:Utility" 
      extension-element-prefixes="ms"
    >
      <xsl:output method="html" version="4.0" />
    
      <ms:script language="jscript" implements-prefix="util">
      <![CDATA[
      function isoDate() {
        var d = new Date();
        return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate())
               + 'T' 
               + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds())
               + '.000Z';
      }
    
      function pad(num) {
        return (num < 10) ? '0' + num : '' + num;
      }
      ]]>
      </ms:script>
    
      <xsl:template match="/">
        <xsl:value-of select="util:isoDate()"/>
      </xsl:template>
    </xsl:stylesheet>