I need to convert 11/14/2016 - This is String Data Type. I need to convert it to 2016-11-14 using XSLT 2.0. Please let me know how to proceed? I don't want to use subString method. I tried format-date() function from xslt 2.0 but not successful.
Asked
Active
Viewed 5,154 times
1
-
Possible duplicate of [How to parse string to date in xslt 2.0](https://stackoverflow.com/questions/16851726/how-to-parse-string-to-date-in-xslt-2-0) – Napoli Apr 24 '18 at 03:48
2 Answers
1
You could do something like this. You can use the tokenize
function instead, if you do not want to use substring.
Assuming an input XML like:
<string>11/14/2016</string>
When run against a style sheet below:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:variable name="target_string">
<xsl:value-of select="tokenize(string, '/')[last()]"/>
<xsl:text>-</xsl:text>
<xsl:value-of select="tokenize(string, '/')[1]"/>
<xsl:text>-</xsl:text>
<xsl:value-of select="tokenize(string, '/')[2]"/>
</xsl:variable>
<date1>
<xsl:value-of select="xs:date($target_string)"/>
</date1>
<date2>
<xsl:value-of select="format-date(xs:date($target_string), '[MNn] [D], [Y]')"/>
</date2>
</xsl:template>
</xsl:stylesheet>
produces:
<date1>2016-11-14</date1><date2>November 14, 2016</date2>

Joel M. Lamsen
- 7,143
- 1
- 12
- 14
-
I tried with above example and got this error below: Could not transform xml with the given xslt. Reason: Invalid date "--" (Year is less than four digits) - My input was - 11/14/2016 – Rajesh Kumar Apr 24 '18 at 18:12
-
I do not know how you implement it, but the code itself is working. See it here (http://xsltfiddle.liberty-development.net/eiZQaEY) – Joel M. Lamsen Apr 25 '18 at 06:29
0
Sorry to say that XSLT is following ISO 8601 which should be yyyy-mm-dd, so subString will be your only choice.

Thomas Choy
- 321
- 2
- 13
-
Thank you Thomas.One more question - I have multiple date tags in incoming XML. How would I achieve that with one date template? Do I have to create separate templates for each tag? – Rajesh Kumar Apr 24 '18 at 04:03
-
Not sure what is your exact requirement, but you can try functions, reference: https://www.xml.com/pub/a/2003/09/03/trxml.html – Thomas Choy Apr 24 '18 at 17:16