Re: [xsl] XSLT 2.0/XPath 2.0 Date arithmetic

Subject: Re: [xsl] XSLT 2.0/XPath 2.0 Date arithmetic
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Wed, 17 May 2006 18:33:05 -0400
Dear Charles,

The new time-and-date data types work very well for this stuff. First contrive a way to cast your date string to an honest date value (this will involve munging its format a bit to the normative 'YYYY-MM-DD' arrangement, then casting it). At that point you can simply "subtract" days from it. Date arithmetic allows the addition and subtraction of dayTimeDuration values from dates (and times): very handy.

Here's a snippet of code that does something not dissimilar:

<xsl:variable name="day" select="xdt:dayTimeDuration('P1D')"/>

<xsl:variable name="thisMonday"
   select="(for $d in (0 to 6) return
     ($today - ($d * $day)))[format-date(.,'[F]')='Monday']"/>

Given a date value $today, $thisMonday is bound to the immediately-preceding Monday. That is, if $today is (a date value) '2006-05-17', the select expression here iterates over $today and the immediately-preceding six days, and returns those members of the sequence that turn out to be Mondays (which happens to be '2006-05-15'; but if $today were 2006-06-01, $thisMonday would be 2006-05-29).

The short version: if $today = xs:date($string) (and $string is in the form of "2006-05-17"), then

$tMinus1 = ($today - xdt:dayTimeDuration('P1D'))

I'm finding both Mike Kay's XPath 2.0 book, and Jeni Tennison's Learning XSLT 2.0 book, to be invaluable for figuring all this out. Honestly, I don't know what we'd do without them.


At 05:29 PM 5/17/2006, you wrote:
Given a parameter, let's call it "today" in the form of this string "20060517", how do I create a variable, let's call it "tMinus1" such that it represents a day earlier than "20060517", that would be "20060516". So long as "$today" isn't the first day of a month, a simple subtraction and followed by a type cast that I don't grasp would do the trick.

What I'm looking for is guidance on date arithmetic.


Charles Knell
cknell@xxxxxxxxxx - email

Wendell Piez                            mailto:wapiez@xxxxxxxxxxxxxxxx
Mulberry Technologies, Inc.      
17 West Jefferson Street                    Direct Phone: 301/315-9635
Suite 207                                          Phone: 301/315-9631
Rockville, MD  20850                                 Fax: 301/315-8285
  Mulberry Technologies: A Consultancy Specializing in SGML and XML

Current Thread