Monday, August 09, 2004

How to Convert and Sort Dates in XSL : Small Tip..

Sometimes small things comes pretty handy. Like this one;

Scenario : Pick the biggest date from the list of dates.

Solution:

  • Converting a Date from one format to another
  • Sort them in ascending order.
  • Pick the first Date from the list ( thats the one you looking for ;) )

Assume your input XML is something like this (Date format is YYYYMMDDTHH:MM:SS)


<DateList>
<Date>20040931T18:31:04</Date> <Date>20040831T18:31:04</Date> <Date>20040715T18:31:04</Date> <Date>20041223T18:31:04</Date>
</DateList>

XSL file

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform;
<xsl:template match="/">
<xsl:for-each select="DateList/Date">
<xsl:sort order="ascending" select="translate(.,'T::', ',')"/>
<xsl:if test="position() = last()">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>


This will print output as
20041223T18:31:04

This is biggest date. you can also print the date in a different format.

  • translate() : does the same job as search and replace
  • ".,'T::', ',' " : "." means Date node value, "T: : ',' " means search for T and : and replace with ' ' (blank space)
  • position() = last()" : means if current index == last index (position(): returns current index)

Happy XSLTingggg!!..

No comments: