XML technologies / XSLT / XSLT Cookbook / Dates and times / Formatting dates and times
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
You want to format dates and times based on a format string.
Solution
These templates use the templates already presented in this chapter. format-date-time uses a format string, where %x is a formatting instruction (see below) and all other text is output literally. The default is the ISO date/time format for Gregorian dates:
<xsl:template name="ckbk:format-date-time">
<xsl:param name="year"/>
<xsl:param name="month"/>
<xsl:param name="day"/>
<xsl:param name="hour"/>
<xsl:param name="minute"/>
<xsl:param name="second"/>
<xsl:param name="time-zone"/>
<xsl:param name="format" select="'%Y-%m-%dT%H:%M:%S%z'"/>
<xsl:choose>
<xsl:when test="contains($format, '%')">
<xsl:value-of select="substring-before($format, '%')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$format"/>
</xsl:otherwise>
</xsl:choose>
<xsl:variable name="code" select="substring(substring-after($format, '%'), 1, 1)"/>
<xsl:choose>
<!-- Abgekürzter Wochentagsname -->
<xsl:when test="$code='a'">
<xsl:variable name="day-of-the-week">
<xsl:call-template name="ckbk:calculate-day-of-the-week">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
</xsl:call-template>
</xsl:variable>
<xsl:call-template name="ckbk:get-day-of-the-week-abbreviation">
<xsl:with-param name="day-of-the-week" select="$day-of-the-week"/>
</xsl:call-template>
</xsl:when>
<!-- Vollständiger Wochentagsname -->
<xsl:when test="$code='A'">
<xsl:variable name="day-of-the-week">
<xsl:call-template name="ckbk:calculate-day-of-the-week">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
</xsl:call-template>
</xsl:variable>
<xsl:call-template name="ckbk:get-day-of-the-week-name">
<xsl:with-param name="day-of-the-week" select="$day-of-the-week"/>
</xsl:call-template>
</xsl:when>
<!-- Abgekürzter Monatsname -->
<xsl:when test="$code='b'">
<xsl:call-template name="ckbk:get-month-abbreviation">
<xsl:with-param name="month" select="$month"/>
</xsl:call-template>
</xsl:when>
<!-- Vollständiger Monatsname -->
<xsl:when test="$code='B'">
<xsl:call-template name="ckbk:get-month-name">
<xsl:with-param name="month" select="$month"/>
</xsl:call-template>
</xsl:when>
<!-- Datums- und Uhrzeitrepräsentation entsprechend der Lokalisierung -->
<xsl:when test="$code='c'">
<xsl:text>[not implemented]</xsl:text>
</xsl:when>
<!-- Tag des Monats als Dezimalzahl (01 - 31) -->
<xsl:when test="$code='d'">
<xsl:value-of select="format-number($day,'00')"/>
</xsl:when>
<!-- Stunde im 24-Stunden-Format (00 - 23) -->
<xsl:when test="$code='H'">
<xsl:value-of select="format-number($hour,'00')"/>
</xsl:when>
<!-- Stunde im 12-Stunden-Format (01 - 12) -->
<xsl:when test="$code='I'">
<xsl:choose>
<xsl:when test="$hour = 0">12</xsl:when>
<xsl:when test="$hour < 13">
<xsl:value-of select="format-number($hour,'00')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="format-number($hour - 12,'00')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<!-- Tag des Jahres als Dezimalzahl (001 - 366) -->
<xsl:when test="$code='j'">
<xsl:variable name="diff">
<xsl:call-template name="ckbk:date-difference">
<xsl:with-param name="from-year" select="$year"/>
<xsl:with-param name="from-month" select="1"/>
<xsl:with-param name="form-day" select="1"/>
<xsl:with-param name="to-year" select="$year"/>
<xsl:with-param name="to-month" select="$month"/>
<xsl:with-param name="to-day" select="$day"/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="format-number($diff + 1, '000')"/>
</xsl:when>
<!-- Monat als Dezimalzahl (01 - 12) -->
<xsl:when test="$code='m'">
<xsl:value-of select="format-number($month,'00')"/>
</xsl:when>
<!-- Minute als Dezimalzahl (00 - 59) -->
<xsl:when test="$code='M'">
<xsl:value-of select="format-number($minute,'00')"/>
</xsl:when>
<!-- AM/PM-Indikator der aktuellen Lokalisierung für die 12-Stunden-Uhr -->
<xsl:when test="$code='p'">
<xsl:choose>
<xsl:when test="$hour < 12">AM</xsl:when>
<xsl:otherwise>PM</xsl:otherwise>
</xsl:choose>
</xsl:when>
<!-- Sekunde als Dezimalzahl (00 - 59) -->
<xsl:when test="$code='S'">
<xsl:value-of select="format-number($second,'00')"/>
</xsl:when>
<!-- Woche des Jahres als Dezimalzahl, mit Sonntag als erstem Tag der Woche (00 - 53) -->
<xsl:when test="$code='U'">
<!-- add 1 to day -->
<xsl:call-template name="ckbk:calculate-week-number">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day + 1"/>
</xsl:call-template>
</xsl:when>
<!-- Wochentag als Dezimalzahl (0 - 6; Sonntag ist 0) -->
<xsl:when test="$code='w'">
<xsl:call-template name="ckbk:calculate-day-of-the-week">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
</xsl:call-template>
</xsl:when>
<!-- Woche des Jahres als Dezimalzahl, mit Montag als erstem Tag der Woche (00 - 53) -->
<xsl:when test="$code='W'">
<xsl:call-template name="ckbk:calculate-week-number">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
</xsl:call-template>
</xsl:when>
<!-- Datumsrepräsentation für die aktuelle Lokalisierung -->
<xsl:when test="$code='x'">
<xsl:text>[not implemented]</xsl:text>
</xsl:when>
<!-- Zeitrepräsentation für die aktuelle Lokalisierung -->
<xsl:when test="$code='X'">
<xsl:text>[not implemented]</xsl:text>
</xsl:when>
<!-- Jahr ohne Jahrhundert als Dezimalzahl (00 - 99) -->
<xsl:when test="$code='y'">
<xsl:value-of select="format-number($year mod 100,'00')"/>
</xsl:when>
<!-- Jahr mit Jahrhundert als Dezimalzahl -->
<xsl:when test="$code='Y'">
<xsl:value-of select="format-number($year,'0000')"/>
</xsl:when>
<!-- Zeitzonenname oder -abkürzung; keine Zeichen, falls Zeitzone unbekannt ist -->
<xsl:when test="$code='z'">
<xsl:value-of select="$time-zone"/>
</xsl:when>
<!-- Prozentzeichen -->
<xsl:when test="$code='%'">
<xsl:text>%</xsl:text>
</xsl:when>
</xsl:choose>
<xsl:variable name="remainder" select="substring(substring-after($format, '%'), 2)"/>
<xsl:if test="$remainder">
<xsl:call-template name="ckbk:format-date-time">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
<xsl:with-param name="hour" select="$hour"/>
<xsl:with-param name="minute" select="$minute"/>
<xsl:with-param name="second" select="$second"/>
<xsl:with-param name="time-zone" select="$time-zone"/>
<xsl:with-param name="format" select="$remainder"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="ckbk:format-julian-day">
<xsl:param name="julian-day"/>
<xsl:param name="format" select="'%Y-%m-%d'"/>
<xsl:variable name="a" select="$julian-day + 32044"/>
<xsl:variable name="b" select="floor((4 * $a + 3) div 146097)"/>
<xsl:variable name="c" select="$a - floor(($b * 146097) div 4)"/>
<xsl:variable name="d" select="floor((4 * $c + 3) div 1461)"/>
<xsl:variable name="e" select="$c - floor((1461 * $d) div 4)"/>
<xsl:variable name="m" select="floor((5 * $e + 2) div 153)"/>
<xsl:variable name="day" select="$e - floor((153 * $m + 2) div 5) + 1"/>
<xsl:variable name="month" select="$m + 3 - 12 * floor($m div 10)"/>
<xsl:variable name="year" select="$b * 100 + $d - 4800 + floor($m div 10)"/>
<xsl:call-template name="ckbk:format-date-time">
<xsl:with-param name="year" select="$year"/>
<xsl:with-param name="month" select="$month"/>
<xsl:with-param name="day" select="$day"/>
<xsl:with-param name="format" select="$format"/>
</xsl:call-template>
</xsl:template>XSLT 2.0
Use the date-formatting functions of XSLT 2.0. In the following fragment, I assume your date is a string in the form JJJJMMTT, which is more common than the ISO date format required by format-date:
<xsl:param name="date" as="xs:string"/>
<invoiceDate>
<xsl:value-of select="format-date(xs:date(concat(substring($date,1,4),'-',substring($date,5,2),'-',substring($date,7,2))),'[MNn] [D01], [Y0001]')"/>
</invoiceDate>
For $date='20050811', this would output:
<invoiceDate>August 11, 2005</invoiceDate>Discussion
XSLT 1.0
This example was made possible by all the date processing in the preceding examples. Options requiring localization are not implemented, but could be implemented using extension functions (see Code generation).
XSLT 2.0
The following is an excerpt from the W3C specification.
Three functions represent dates and times as strings using the conventions of a selected calendar and locale. Each has two variants:
format-dateTime($value as xs:dateTime?,
$picture as xs:string,
$date-format-name as xs:string) as xs:string?
format-dateTime($value as xs:dateTime?, $picture as xs:string) as xs:string?
format-date($value as xs:date?,
$picture as xs:string,
$date-format-name as xs:string) as xs:string?
format-date($value as xs:date?, $picture as xs:string) as xs:string?
format-time($value as xs:time?,
$picture as xs:string,
$date-format-name as xs:string) as xs:string?
format-time($value as xs:time?, $picture as xs:string) as xs:string?The functions format-dateTime, format-date and format-time format $value as a string using the picture string specified by the argument $picture and the date format named by the argument $date-format-name. If there is no $date-format-name argument, the default date format is used. The function returns the formatted string representation of the supplied values dateTime, date or time.
The three functions format-dateTime, format-date and format-time are collectively called date-formatting functions.
It is a dynamic error if the name supplied as the $date-format-name argument is not a valid QName, its prefix is not declared in a namespace declaration, or the stylesheet contains no declaration of a date-format with a matching expanded-QName. The processor must either signal the error or continue by ignoring the argument $date-format-name. If the processor can detect the error statically—for example, if the argument is a string literal—it may optionally report it as a static error.
If $value is an empty sequence, an empty sequence is returned.
The date-format declaration
<!-- Kategorie: Deklaration -->
<xsl:date-format name = qname
language = nmtoken
calendar = qname />The element xsl:date-format declares a date format supplying information used by the date-formatting functions. If a name attribute exists, the element declares a named date format; otherwise it declares the default date format. The value of attribute name is a QName. It is a static error to declare either the default date-format or a date format with a particular name more than once, even at different import precedence, unless every declaration gives all attributes the same values, taking defaults into account. If the stylesheet has no default date format declaration, a declaration equivalent to a xsl:date-format element without attributes is implicitly assumed.
The attribute language specifies the language used by the function format-date for its result string. The attribute’s effective value must be valid for the attribute xml:lang. If the language attribute is omitted, the default is implementation-defined.
The language selects appropriate language-dependent forms:
Names (for example, months)
Ordinal forms of numbers
Hour conventions (0–23 or 1–24, 0–11 or 1–12)
First day of the week, first week of the year
Supported languages depend on the implementation.
The attribute calendar specifies that dateTime, date or time supplied in the argument $value must be converted to a value in this calendar, then converted to a string using that calendar’s conventions.
A calendar value must be a valid QName. If the QName has no prefix, it identifies the calendar with the identifier given below. If QName has a prefix, the QName is expanded to an expanded-QName. The expanded-QName identifies the calendar; behavior in this case is not specified by this document.
If the calendar attribute is omitted, a locale-specific value is used.
It is a static error if an implementation does not support the language specified by the attribute language, the calendar specified by the attribute calendar, or their combination. The processor must signal the error or continue using locale-specific values for these attributes instead of the specified values. If a different calendar is used than requested, its name must be included in the result string.
Note:
The calendars listed next have been used at least within the last hundred years. Many other calendars were used earlier and often cannot be fully supported without additional parameters. These could be defined with further attributes on the element xsl:date-format prefixed with a namespace, but this specification does not define their semantics.
This specification does not define any of these calendars or how they map to the value space of the xs:date datatype in XML Schema. Dates recorded using different calendars are only approximately equivalent. For example, a new day does not begin simultaneously in different calendars and may also vary geographically. Implementations supporting calendars other than Gregorian may therefore produce different results.
Identifier | Calendar |
AD | Anno Domini (Christian era) |
AH | Anno Hegirae (Muhammadan era) |
AME | Mauludi era (solar years since Muhammad’s birth) |
AM | Anno Mundi (Jewish calendar) |
AP | Anno Persici |
AS | Aji Saka era (Java) |
BE | Buddhist era |
CB | Cooch Behar era |
CE | Common Era |
CL | Chinese lunar era |
CS | Chula Sakarat era |
EE | Ethiopian era |
FE | Fasli era |
ISO | ISO 8601 calendar |
JE | Japanese calendar |
KE | Khalsa era (Sikh calendar) |
KY | Kali Yuga |
ME | Malabar era |
MS | Monarchic solar era |
NS | Nepal Samwat era |
OS | Old Style (Julian calendar) |
RS | Rattanakosin (Bangkok) era |
SE | Saka era |
SH | Muhammadan solar era (Iran) |
SS | Saka Samvat |
TE | Tripurabda era |
VE | Vikrama era |
VS | Vikrama Samvat era |
At least one listed calendar must be supported. Which one is implementation-defined.
The ISO 8601 calendar, identified as ISO in the list above, is essentially the same as the Gregorian calendar identified as AD, but requires the numbering conventions defined in ISO 8601 rather than language-based localization. In particular, ISO weekdays are numbered 1 (Monday) to 7 (Sunday), and week 1 of a calendar year is the Monday-to-Sunday week containing that year’s first Thursday. The numeric year, month, day, hour, minute and second components equal those used in the lexical date/time representation defined by XML Schema. The ISO calendar is intended primarily for applications producing dates and times for other programs rather than human users.
Note:
The value space of the datatypes for dates and times defined by XML Schema is based on absolute instants in time. Their lexical space represents these instants using the proleptic Gregorian calendar: the modern Western calendar is extrapolated into the past and future, recalculating historical dates in Gregorian terms. The value space itself is calendar-neutral. Date-formatting functions represent the same absolute instant in a potentially different calendar. For example, the date whose XML Schema lexical representation is 1502-01-11 (the day Pope Gregory XIII was born) could be formatted using the Julian (Old Style) calendar as 1 January 1502. This reflects the ten-day difference between the calendars at that time. Representing this date in an element or attribute of type xs:date as 1502-01-01 would be wrong and yield incorrect results, even if it reflected how the date was recorded in contemporary documents.
The picture string
The picture string consists of variable markers and literal substrings. A substring enclosed in square brackets is interpreted as a variable marker; substrings outside square brackets are treated as literal substrings. Literal substrings are optional and, if present, reproduced unchanged, including all whitespace characters. To include an opening or closing square bracket in a literal substring, double it. Variable markers are replaced in the result by strings representing aspects of the date and/or time to format, as described below.
A variable marker consists of a component specifier, optionally followed by one or two presentation modifiers and/or a length modifier. Whitespace inside a variable marker is ignored.
The component specifier identifies the required date or time component and may have these values:
Specifier | Meaning | Default presentation modifier |
Y | Year | 1 |
M | Month within year | 1 |
D | Day within month | 1 |
d | Day within year | 1 |
F | Day of week | n |
W | Week within year | 1 |
w | Week within month | 1 |
H | Hour within day (24 hours) | 1 |
h | Hour within half-day (12 hours) | 1 |
P | a.m./p.m. marker | n |
m | Minute within hour | 1 |
s | Second within minute | 1 |
f | Fractional seconds | 1 |
Z | Time zone as an offset from UTC or, with an alphabetic modifier, its conventional name (such as PST). | 1 |
z | Time zone as an offset using GMT, for example GMT+1. | 1 |
C | Calendar: name or abbreviation of a calendar name | n |
E | Era: name of a basis for numbering years, such as a monarch’s reign | n |
It is a dynamic error if a component specifier in the picture string refers to components unavailable in the supplied $value or unsupported by the selected calendar. This is a recoverable error. The processor may signal the error or continue by ignoring the inappropriate component specifiers.
The first presentation modifier identifies the style for representing the component’s value and takes these values:
Modifier | Meaning |
A | Alphabetic, uppercase |
a | Alphabetic, lowercase (may begin with uppercase if customary in the language) |
N | Name, uppercase |
n | Name, lowercase (may begin with uppercase if customary in the language) |
Digit 1 | Decimal representation |
i | Lowercase Roman numeral |
I | Uppercase Roman numeral |
Any character with decimal digit value 1 (as defined in the Unicode character properties database) produces a decimal representation of the number using the corresponding set of Unicode digits.
Any other character may identify a numbering sequence starting with that character, if the implementation supports such a sequence.
If the implementation does not support the requested presentation modifier, use the default modifier for this component.
If the first presentation modifier is present, a second may optionally follow it:
Modifier | Meaning |
T | Traditional numbering. Same meaning as |
O | Ordinal form of a number, such as 3rd or 8º. |
Whether or not a presentation modifier exists, a width modifier may be specified, determining the number of characters or digits that can be included in the value’s representation.
The width modifier has this form:
min-breite ("-" max-breite)?
where min-breite is either an unsigned integer specifying the minimum number of output characters or *, indicating no explicit minimum. max-breite is either an unsigned integer specifying the maximum number of output characters or *, indicating no explicit maximum. If max-breite is omitted, * is assumed. Both integers, if present, must exceed zero.
Without a width modifier, output uses as many characters as needed to represent the component’s value without truncation or padding. This is called the value’s full representation.
If the full representation exceeds the specified maximum width, the processor should try a shorter alternative that fits. If the presentation modifier is n or N, this is done by abbreviating the name, using conventional abbreviations where available or otherwise truncating on the right. For example, setting max-breite to 4 requests four-letter abbreviations, although a customary three-letter abbreviation is also acceptable (e.g. “Tuesday” to “Tues”, “Friday” to “Fri”). For the year component, setting max-breite causes higher-order year digits to be omitted. For example, setting max-breite to 2 outputs 2003 as 03. If there is no way to fit the value into the maximum width, such as with Roman numerals, its full representation should be output.
If the full representation is shorter than the minimum width, the processor should pad it to that width. Decimal numbers are padded with leading zeros from the corresponding digit set. Other representations should use leading spaces.
The names and abbreviations used in a language are implementation-defined. For example, one implementation might abbreviate July as Jul, while another uses Jly. In German, one implementation might call Saturday Samstag, while another calls it Sonnabend. Implementations may offer mechanisms allowing users to control such choices.
The examples below show selected dates and times and how they might be formatted. They assume the Gregorian calendar and that names of the stylesheet’s xsl:date-format declarations match the value of the attribute language (for example, <date-format name="sv" language="sv"/>).
Required output | Expression |
2002-12-31 | format-date($d,"[Y]-[M]-[D]") |
12-31-2002 | format-date($d,"[M]-[D]-[Y]") |
31-12-2002 | format-date($d,"[D]-[M]-[Y]") |
31 XII 2002 | format-date($d,"[D1] [MI] [Y]") |
31st December, 2002 | format-date($d,"[Do] [Mn], [Y]", "en") |
31 DEC 2002 | format-date($d,"[D] [MN,*-3] [Y]", "en") |
December 31, 2002 | format-date($d,"[Mn] [D], [Y]", "en") |
31 Dezember, 2002 | format-date($d,"[D] [Mn], [Y]", "de") |
Tisdag 31 December 2002 | format-date($d,"[Fn] [D] [Mn] [Y]", "sv") |
[2003-04-07] | format-date($t,"[[[Y]-[M]-[D]]]") |
3:58 PM | format-time($t,"[h]:[m] [PN]", "en") |
3:58:45 pm | format-time($t,"[h]:[m]:[s] [Pn]", "en") |
3:58:45 PM PDT | format-time($t,"[h]:[m]:[s] [PN] [ZN,*-3]", "en") |
3:58:45 o'clock PM PDT | format-time($t,"[h]:[m]:[s] o'clock [PN] [ZN,*-3]", "en") |
15:58 | format-time($t,"[H]:[m]") |
15:58:45 | format-time($t,"[H]:[m]:[s]") |
15:58:45 GMT+02:00 | format-time($t,"[H]:[m]:[s] [z]", "en") |
15.58 Uhr GMT+02:00 | format-time($t,"[H]:[m]:[s] Uhr [z]", "de") |
The following examples use calendars other than Gregorian:
<!-- Beispiel: Thai -->
<xsl:date-format name="modern_Thai" language="th" calendar="BE"/>
format-date($d, "[D๑] [Mn] [Y๑]", "modern_Thai")
<!-- Ergebnis: ๓๑ ธันวาคม ๒๕๕๕ -->
<!--Beispiel: Islamisch-->
<xsl:date-format name="Islamic" language="ar" calendar="AH"/>
format-date($d, "[D١] [Mn] [Y١]", "Islamic")
<!-- Ergebnis: ١٤٣٣ تمو׳ال ٢٦ -->
<!--Beispiel: Jüdisch-->
<xsl:date-format name="Jewish" language="he" calendar="AM"/>
format-date($d, "[D] [Mn] [Y]", "Jewish")
<!--Ergebnis: 26 טבת 5763 -->
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de