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!!..

4 comments:

final fantasy 10 2 cheatbf said...

Exciting blog. Your site was amazing and will be
back again! I never get tired of looking for blogs
just like this one.
Come as you are and look at my 3220 nokia shell wave blog.

job opportunitya said...

Awesome blog. I'm loving the site and I have to
return there soon! Going online, when I have the time,
I look for blogs close to your work!
Stop by and look at my male plastic surgery blog site.

job opportunitya said...

Excellent blog.  I go though the web in search of
blogs like this one. Its so good, that I plan on
returning to its site!
I know that you love my work so, look up my disapointments plastic surgery blog.

after-glow said...

Awesome blog. I'm loving the site and I have to
return there soon! Going online, when I have the time,
I look for blogs close to your work!
No matter when you are, just stop by and check for my advance america cash advance center blog site.