CodeGuru
CodeGuru

Reputation: 2803

Format date in xslt

I have following xml

  <Report>
     <Items>
       <Item>
        <Id>1</Id>
        <TotalSent>251</TotalSent>
        <Opened>48</Opened>
        <LastSend>01/07/2013 16:38:18</LastSend>
        <Bounced>1</Bounced>
        <Unopened>202</Unopened>
      </Item>
    </Items>
  </Report>

i want to transform it to another xml using xslt , my desired o/p is like below

<chart subcaption ="Last sent on Monday 01 July 2013 at 16:38">
  <set label="Opened" value="48"/>
  <set label="Bounced" value="1"/>
</chart>

I am not able to get date as i want for subcaption attribute. I tried below xslt code but it is not working

<?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">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
<xsl:template match="/">
    <chart>
      <xsl:variable name='lastSend' select='Report/Items/Item/LastSend' />
      <xsl:attribute name="subcaption">
        <xsl:value-of select="ms:format-date($lastSend, ' Last sent on MMM dd, yyyy at')"/>
        <xsl:value-of select="ms:format-time($lastSend, ' hh:mm')"/>
      </xsl:attribute>
      <xsl:for-each select="Report/Items/Item">
        <set>
          <xsl:attribute name="label">Opened</xsl:attribute>
          <xsl:attribute name="value">
            <xsl:value-of select="Opened" />
          </xsl:attribute>
        </set>
        <set>
          <xsl:attribute name="label">Bounced</xsl:attribute>
          <xsl:attribute name="value">
            <xsl:value-of select="Bounced" />
          </xsl:attribute>
        </set>
      </xsl:for-each>
    </chart>
  </xsl:template>
</xsl:stylesheet>

when i am passing hard coded value in ms:format-date() & ms:format-time() functions, like 01/07/2013 16:38:18 it was working fine , but when i am passing variable value $lastSend it is not working.

Note: I can use any version of xsl.

Upvotes: 1

Views: 18054

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

If you want to use XSLT 2.0 then you need to convert your custom date respectively dateTime format into an xs:dateTime and then you can use the format-dateTime function that XSLT 2.0 provides (see http://www.w3.org/TR/xslt20/#format-date):

<xsl:template match="LastSend">
  <!-- 01/07/2013 16:38:18 -->
  <xsl:variable name="dt" as="xs:dateTime" select="xs:dateTime(concat(substring(., 7, 4), '-', substring(., 4, 2), '-', substring(., 1, 2), 'T', substring(., 12)))"/>
  <xsl:attribute name="subcaption" select="format-dateTime($dt, 'Last sent on [F] [D01] [MNn] [Y0001] at [H01]:[m01]')"/>
</xsl:template>

Take the above second argument "picture string" as an example on how to format a dateTime, you might need to adjust it for your needs, based on the picture string arguments documented in the XSLT 2.0 specification.

Upvotes: 3

Related Questions