Ashok.N
Ashok.N

Reputation: 1391

Get current time in the format YYYY-MM-DD-HH.MI.Sec.Ms using XSLT

I have the following xml:

<root>
<Test>tested</Test>
</root>

Now, I want to add the current date time stamp in the format YYYY-MM-DD-HH.MI.Sec.Ms to a new node for the above xml using XSLT. For example my resultant xml should look like below:

<root>
<Test>tested</Test>
<dateTimeStamp>2014-05-21-01.25.32.000000</dateTimeStamp> 
</root>

Can anybody help me on this?

Can you please add the code for XSLT 1.0 also so that I can find the difference? I will give +1 for that.

Upvotes: 2

Views: 14327

Answers (2)

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

try something like:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <xsl:strip-space elements="*"/>

    <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/root">
        <xsl:variable name="timeNoMs" select="translate(substring-before(substring-before(string(current-time()), '+'), '.'), ':', '.')"/>
        <xsl:variable name="timeMs" select="format-number(number(substring-after(substring-before(string(current-time()), '+'), '.')), '##0000')"/>
        <xsl:copy>
            <xsl:copy-of select="node()|@*"/>
            <dateTimeStamp><xsl:value-of select="concat(substring-before(string(current-date()), '+'), '-', $timeNoMs, $timeMs)"/></dateTimeStamp>
        </xsl:copy>
    </xsl:template>    

</xsl:stylesheet>

Upvotes: 2

Daniel Haley
Daniel Haley

Reputation: 52858

You can use format-dateTime()...

XSLT 2.0

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="/*">
        <xsl:copy>
            <xsl:copy-of select="@*|node()"/>
            <dateTimeStamp>
                <xsl:value-of select="format-dateTime(current-dateTime(),'[Y0001]-[M01]-[D01]-[H01].[m01].[s].[f]')"/>
            </dateTimeStamp>
        </xsl:copy>        
    </xsl:template>

</xsl:stylesheet>

Output

<root>
   <Test>tested</Test>
   <dateTimeStamp>2014-05-21-01.44.58.312</dateTimeStamp>
</root>

See http://www.w3.org/TR/2014/REC-xpath-functions-30-20140408/#rules-for-datetime-formatting for more info.

Upvotes: 8

Related Questions