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:dayTimeDuration xs:time + xs:dayTimeDuration xs:datetime + xs:yearMonthDuration xs:datetime + xs:dayTimeDuration xs:yearMonthDuration + xs:yearMonthDuration xs:dayTimeDuration + xs:dayTimeDuration |
- | Subtraction | xs:date – xs:date xs:date – xs:yearMonthDuration xs:date – xs:dayTimeDuration xs:time – xs:time xs:time – xs:dayTimeDuration xs:datetime – xs:datetime xs:datetime – xs:yearMonthDuration xs:datetime – xs:dayTimeDuration xs:yearMonthDuration – xs:yearMonthDuration xs:dayTimeDuration – xs:dayTimeDuration |
* | Multiplication | xs:decimal * xs:yearMonthDuration xs:decimal * xs:dayTimeDuration |
div | Division | xs:yearMonthDuration xs:decimal xs:dayTimeDuration xs:decimal |
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.
Copyright © Galileo Press, Bonn 2008
You may print the online version for your private use.
Otherwise, this chapter from "XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch" is subject to the same terms as the printed edition: the work and all its parts are protected by copyright. All rights are reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
Galileo Press, Rheinwerkallee 4, 53227 Bonn