[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] Compare dates in xsl. Is posible?


Subject: Re: [xsl] Compare dates in xsl. Is posible?
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Tue, 12 Mar 2002 18:15:48 +0000

Hi Carlos,

> In a xml file i have a field with the date (2002-03-01)
> in a xsl template can i compare this date with the today date?
> how?
> i want to make a thing if is minor that 7 days.
> is this posible?

It's possible, but not straight-forward.

First, there's no way in XPath 1.0 to find out what today's date is
from within a stylesheet. There are two ways around this: you can pass
today's date in as a parameter to the stylesheet, or you can use an
extension function such as date:date-time() (see
http://www.exslt.org/date/functions/date-time). The date:date-time()
extension function is implemented natively in Saxon and there's a
MSXML version courtesy of Chris Bayes available from the above URL.

Second, there's no way in XPath 1.0 to add or subtract days from a
date. If you're passing in the current date as a parameter, it's
probably easiest to actually pass in the current date minus a week.
Otherwise, you can use date:add-duration() (see
http://www.exslt.org/date/functions/add-duration), which is available
written in XSLT or in JavaScript for MSXML. To get today's date minus
7 days, for example, you can do:

  date:add-duration(date:date-time(), '-P2D')

Finally, there's no way in XPath 1.0 to compare two dates in the format
CCYY-MM-DD. However, this is fairly easy to get round if you convert
the dates to numbers by deleting the -s with the translate() function.

For example, if the date is held in the date attribute, then you could
do:

  translate(date:add-duration(date:date-time(), '-', ''), '-P2D') >
  translate(@date, '-', '')

Hopefully, this will all be a lot easier in XPath 2.0...
  
Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list



Current Thread
Keywords