XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / Date, duration and timestamp values / Time with fn:current-time()

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

Just as you can obtain the current date, you can obtain the current system time using fn:current-time(), which returns a time value xs:time with a string representation such as 20:58:23.125+01:00 or similar:

<xsl:variable name="uhrzeit" select="fn:current-time()"/>
  

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

Formatting uses the XSLT function format-time() which works essentially like format-date().

<p>Es ist jetzt <xsl:value-of select="format-time($uhrzeit,'[H01]:[m01]')"/> Uhr und <xsl:value-of select="format-time($uhrzeit,'[s01]')"/> Sekunden.</p>

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

Since the time is stored in a variable, it can easily be used twice: first to extract and output the hours and minutes, then the seconds.

There is a simpler approach here: besides specifiers identifying the time components to extract, the formatting string can contain arbitrary literals. The same result can therefore be produced in one call:

<p><xsl:value-of select="format-time($uhrzeit,'Es ist jetzt [H01]:[m01] Uhr und [s01] Sekunden.')"/></p>

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

Both versions produce output such as “Es ist jetzt 21:30 Uhr und 50 Sekunden”. To use a 12-hour clock instead of a 24-hour clock, slightly change the formatting string:

format-time($uhrzeit,'Es ist jetzt [h01]:[m01] Uhr')

produces “Es ist jetzt 09:30 Uhr”. It is useful here to indicate morning or afternoon. This component is obtained with the specifier P:

format-time($uhrzeit,'Es ist jetzt [h01]:[m01] Uhr [P]')

produces “Es ist jetzt 09:30 Uhr p.m.”.

   

back to top