Formatting Dates and Times

Problem

You want to format dates and times based on a format string.

Solution

These templates reuse many of the templates already presented in this chapter. The format-date-time uses a format string where %x is a formatting directive (see later) and all other text is output literally. The default format is the ISO date-time format for Gregorian dates:

<xsl:template name="date: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> <!-- Abbreviated weekday name --> <xsl:when test="$code='a'"> <xsl:variable name="day-of-the-week"> <xsl:call-template name="date: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="date:get-day-of-the-week-abbreviation"> <xsl:with-param name="day-of-the-week" select="$day-of-the-week"/> </xsl:call-template> </xsl:when> <!-- Full weekday name --> <xsl:when test="$code='A'"> ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.