Naor
Naor

Reputation: 24063

format and display datetime in xslt

I have an XML with datetime data:

<A>
    <StartDate>2011-11-01T00:00:00</StartDate>
    <EndDate>2011-11-30T00:00:00</EndDate>
    <IsRecurring>false</IsRecurring>
</A>

I need to get in xslt only the dates in the following format:

01/11/2011 - 30/11/2011

When I do:

<xsl:value-of select="A/StartDate/"> - <xsl:value-of select="A/EndDate/">

I get this:

2011-11-01T00:00:00 - 2011-11-30T00:00:00

How can I display it properly?

Upvotes: 15

Views: 55028

Answers (3)

JBert
JBert

Reputation: 3390

EDIT: If you still have to use XSLT 1.x, you could look at EXSLT's date:format-date user function. In that case the pattern is dd/MM/yyyy.

If your are using XSLT 2.0, it is handier to use the format-dateTime function.

Here's your example in XSLT 2.0:

<xsl:value-of select="format-dateTime(A/StartDate, '[D01]/[M01]/[Y0001]')" /> 
- <xsl:value-of select="format-dateTime(A/EndDate, '[D01]/[M01]/[Y0001]')" />

Upvotes: 15

FailedDev
FailedDev

Reputation: 26930

In addition to @Kirill Polishchuk answer if you were using XSLT 2.0 you can simply do a replace :

substring(replace($input, "(\d{4})-(\d{2})-(\d{2})", "$3/$2/$1"), 0, 11)

Where $input is the contents of your nodes which contain the dates.

Upvotes: 1

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Look at XPath string functions: substring, substring-before and etc.

Reference: http://www.w3.org/TR/xpath/#section-String-Functions

<xsl:variable name="dt" select="'2011-11-01T12:13:59'"/>

        <xsl:value-of select="concat(
                      substring($dt, 9, 2),
                      '/',
                      substring($dt, 6, 2),
                      '/',
                      substring($dt, 1, 4)
                      )"/>

Upvotes: 22

Related Questions