XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / Date, duration and timestamp values / Operations on date, time and dateTime values

(Excerpt from "XSLT 2.0 & XPath 2.0" by Frank Bongers, Chapter 3.)

If the required data types for the desired operations are ensured through a constructor or casting, calculations with time, date and dateTime values are straightforward.

The following mathematical operations are available for these value types; the result type is shown in each case:

Operator

Name

Applicable types

+

Addition

xs:date  + xs:yearMonthDuration 

->xs:date

xs:date  + xs:dayTimeDuration 

->xs:date

xs:time  + xs:dayTimeDuration 

->xs:time

xs:datetime  + xs:yearMonthDuration 

-> xs:dateTime

xs:datetime  + xs:dayTimeDuration 

-> xs:dateTime

xs:yearMonthDuration  + xs:yearMonthDuration 

-> xs:yearMonthDuration

xs:dayTimeDuration  + xs:dayTimeDuration

-> xs:dayTimeDuration 

-

Subtraction

xs:date – xs:date 

-> xs:dayTimeDuration

xs:date – xs:yearMonthDuration 

-> xs:date

xs:date – xs:dayTimeDuration 

-> xs:date

xs:time – xs:time 

-> xs:dayTimeDuration

xs:time – xs:dayTimeDuration 

-> xs:time

xs:datetime – xs:datetime 

-> xs:dayTimeDuration

xs:datetime – xs:yearMonthDuration 

-> xs:dateTime

xs:datetime – xs:dayTimeDuration 

-> xs:dateTime

xs:yearMonthDuration – xs:yearMonthDuration

-> xs:yearMonthDuration

xs:dayTimeDuration – xs:dayTimeDuration 

-> xs:dayTimeDuration

*

Multiplication

xs:decimal  *  xs:yearMonthDuration

-> xs:yearMonthDuration

xs:decimal  *  xs:dayTimeDuration

-> xs:dayTimeDuration

div

Division

xs:yearMonthDuration xs:decimal

-> xs:yearMonthDuration

xs:dayTimeDuration xs:decimal

-> xs:dayTimeDuration

Table: Operations on date, time and dateTime values.

For example, to find the difference between two dates, simply subtract one from the other. According to the table above, the result is a duration value xs:dayTimeDuration. The number of days must then be extracted with the function fn:days-from-duration(), because the duration’s string representation is rather cryptic:

<xsl:variable name="heute" select="fn:current-date()"/>
<xsl:variable name="dann" select="'2010-01-01'"/>
<p>Bis zum <xsl:value-of select="format-date(xs:date($dann),'[D1].[M1].[Y0001]')"/> sind es <xsl:value-of select="fn:days-from-duration(xs:date($dann) - $heute)"/> Tage.</p>

Code example: kap03/3.05/date.xsl (excerpt).

Further functions for extracting components from duration values are available: fn:hours-from-duration(), fn:minutes-from-duration(), fn:months-from-duration(), fn:seconds-from-duration() and fn:years-from-duration(). For more information, see chapter 5 of the reference section, XSLT and XPath function reference.

   

back to top