Ripp Porter
Ripp Porter

Reputation: 23

Sorting XSLT by Date AND Time

I'm trying to sort by date/time descending, in a XSLT file and I've been able to accomplish this for the most part, however, the time part is a bit tricky. I'm sorting by "number" instead of the actual "time". For example, my output is:

3/2/2013 10:05 am

3/2/2013 4:28 pm

2/28/2013 5:03 pm

Normally, descending would mean that 10 would come before 4 on that date but when it comes to time, that is not the case. Any suggestions on how i can achieve:

3/2/2013 4:28 pm

3/2/2013 10:05 am

2/28/2013 5:03 pm

Here is the sort that i used:

<xsl:sort select="substring-before(substring-after(substring-after(NoteEnteredOn, '/'), '/'), ' ')" /> <!-- year  -->
<xsl:sort select="substring(normalize-space(NoteEnteredOn),1,2)"/> <!-- month -->
<xsl:sort select ="substring-after(substring-after(normalize-space(NoteEnteredOn), ' '),' ')"/> <!-- AM / PM-->
<xsl:sort select="substring-before(substring-after(substring-after(NoteEnteredOn, ' '),' '),':')" /> <!--Hour-->
<xsl:sort select="substring-before(substring-after(normalize-space(NoteEnteredOn), ':'), ' ')"/> <!--Minute-->
<xsl:sort select="substring-before(substring-after(NoteEnteredOn, '/'), '/')" /> <!-- Day   -->

Upvotes: 2

Views: 2190

Answers (1)

JLRishe
JLRishe

Reputation: 101748

You need to use data-type="number" for the numeric parts, have the sorts arranged in the right order, and use order="descending":

<!-- year  -->
<xsl:sort select="substring-before(substring-after(substring-after(NoteEnteredOn,
        '/'), '/'), ' ')" order="descending" data-type="number" /> 
<!-- month -->
<xsl:sort select="substring(normalize-space(NoteEnteredOn),1,2)"
        order="descending" data-type="number" /> 
<!-- Day   -->
<xsl:sort select="substring-before(substring-after(NoteEnteredOn, '/'), '/')" 
        order="descending" data-type="number" /> 
<!-- AM / PM-->
<xsl:sort select ="substring-after(substring-after(normalize-space(NoteEnteredOn), 
        ' '),' ')" order="descending" /> 
<!--Hour-->
<xsl:sort select="substring-before(substring-after(normalize-space(NoteEnteredOn), 
                   ,' '),':') mod 12" 
          order="descending" data-type="number" /> 
<!--Minute-->
<xsl:sort select="substring-before(substring-after(normalize-space(NoteEnteredOn),
                   ':'), ' ')" 
          order="descending" data-type="number" /> 

Of course, this would be a whole lot easier if your data were in a sortable yyyy-MM-ddTHH:mm:ss format :)

Upvotes: 2

Related Questions