vikram keshari
vikram keshari

Reputation: 73

convert a date value into string date format in xslt

I am getting a date value as '2018-08-03 00:00:00.0' from an xml I need to convert this in the format '08-MAR-2018'. How can I do this? please help.

xsl code to get the date from xml:

<xsl:variable name="createDate" select="$XmlRoot/attributes/attribute[@identifier='createdate']/value"/>

and I want to access it here as:

<value><xsl:value-of select="$createDate"/></value>

-this value need to be in '08-MAR-2018' format.(not necessarily the value should be a date variable, String variable is also okay) I found few references with substring, but need to know how to convert month into JAN, FEB, MAR, etc.

Upvotes: 1

Views: 282

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116993

Try:

<value>
    <xsl:value-of select="substring($createDate, 9, 2)"/>
    <xsl:text>-</xsl:text>
    <xsl:variable name="month" select="substring($createDate, 6, 2)"/>
    <xsl:choose>
        <xsl:when test="$month=1">JAN</xsl:when>
        <xsl:when test="$month=2">FEB</xsl:when>
        <xsl:when test="$month=3">MAR</xsl:when>
        <xsl:when test="$month=4">APR</xsl:when>
        <xsl:when test="$month=5">MAY</xsl:when>
        <xsl:when test="$month=6">JUN</xsl:when>
        <xsl:when test="$month=7">JUL</xsl:when>
        <xsl:when test="$month=8">AUG</xsl:when>
        <xsl:when test="$month=9">SEP</xsl:when>
        <xsl:when test="$month=10">OCT</xsl:when>
        <xsl:when test="$month=11">NOV</xsl:when>
        <xsl:when test="$month=12">DEC</xsl:when>
    </xsl:choose>
    <xsl:text>-</xsl:text>
    <xsl:value-of select="substring($createDate, 1, 4)"/>
</value>

Or, if you prefer:

<value>
    <xsl:value-of select="substring($createDate, 9, 2)"/>
    <xsl:text>-</xsl:text>
    <xsl:variable name="month" select="substring($createDate, 6, 2)" />
    <xsl:value-of select="substring('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC', 3 * ($month - 1) + 1, 3)"/>
    <xsl:text>-</xsl:text>
    <xsl:value-of select="substring($createDate, 1, 4)"/>
</value>

Note that in the given example, where the value of $createDate is 2018-08-03 00:00:00.0, the result will be:

<value>03-AUG-2018</value>

not '08-MAR-2018' as indicated in your question.

Upvotes: 3

Related Questions