A handy addition in XSLT 2.0 is a nice set of date and time format XPath functions. XSLT 1.0 was decidedly lacking in these functions, so you may have used a third-party library such as EXSLT for this purpose. EXSLT offers arithmetic functions on dates and times (still absent in XSLT 2.0) but the XSLT 2.0 offering is perfect for formatting dates and times as strings. It also means that you don't have to worry about importing the third-party library.
The XSLT 2.0 Specification specifies three functions for formatting dates:
- format-dateTime() for a combined date and time
- format-date() for a date
- format-time() for a time
Each of these functions has two variants. The first simply takes the date/time as the first argument, and a Picture as the second. The second variant is a little more complex. As well as taking the date/time and the Picture, it also requires a language. a calendar and a country.
Pictures
A picture string is simple a date format string. The following pictures are available:
Specifier | Meaning | Default Presentation Modifier |
Y | year (absolute value) | 1 |
M | month in year | 1 |
D | day in month | 1 |
d | day in year | 1 |
F | day of week | n |
W | week in year | 1 |
w | week in month | 1 |
H | hour in day (24 hours) | 1 |
h | hour in half-day (12 hours) | 1 |
P | am/pm marker | n |
m | minute in hour | 01 |
s | second in minute | 01 |
f | fractional seconds | 1 |
Z | timezone as a time offset from UTC, or if an alphabetic modifier is present the conventional name of a timezone (such as PST) | 1 |
z | timezone as a time offset using GMT, for example GMT+1 | 1 |
C | calendar: the name or abbreviation of a calendar name | n |
E | era: the name of a baseline for the numbering of years, for example the reign of a monarch | n |
Numbering
Each picture that results in a number must be coupled with a number format token.
Format Token | Sequence |
1 | 1 2 3 ... 100 ... |
A | A B C .... Z AA AB AC ... |
a | a b c ... z aa ab ac ... |
i | i ii iii iv v vi vii .. x .. m .. |
I | I II III IV V VI VII ..... |
w | one two three four ... |
W | ONE TWO THREE FOUR ... |
Ww | One Two Three Four ... |
o | first second third ... |
Zero Padding
Often you will want to pad out some numbers with zeroes to a fixed length. This is performed by prefixing the Format Token with zeroes up to the length required. For example, a format token that would pad the day with zeroes up to four digits would be [D0001].
Examples
Example functions
Example XSLT
The below XSLT has been tested against Saxon EE. (Foreign language support is not included with the open source Home Edition)
Example Output
The resulting output HTML is as follows:
References
http://www.w3.org/TR/xslt20/#function-format-date
http://my.safaribooksonline.com/book/xml/9780596527211/creating-output/xslt-id-4.5