XML technologies / XSLT / XSLT Cookbook / Dates and times / Determine the last day of the month

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

Given a month and year, determine the last day of the month.

Solution

XSLT 1.0

<xsl:template name="ckbk:last-day-of-month">
  <xsl:param name="month"/>
  <xsl:param name="year"/>
  <xsl:choose>
    <xsl:when test="$month = 2 and not($year mod 4) and ($year mod 100 or not($year mod 400))">
      <xsl:value-of select="29"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="substring('312831303130313130313031', 2 * $month - 1,2)"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

 

The logic behind the calculations

Claus Tøndering kindly explained the mystery behind these calculations.

For the formulas to work, first perform these calculations:

a = (14 - monat) / 12 y = jahr - a m = monat + 12*a - 2

These calculations move the start of the year from January 1 to March 1. Since a=1 for January and February and 0 for all other months, 1 is subtracted from the year in those two months. Likewise, m becomes 1 for March, 2 for April, …, 10 for December, 11 for January and 12 for February.

After these calculations, the year starts on March 1. This has two advantages: the leap day falls at the end of the year, simplifying calculations, and month lengths follow a simple pattern:

31 30 31 30 31 (März-Juli) 31 30 31 30 31 (August-Dezember) 31 X (Januar-Februar)

This arrangement lets you use expression (31*m)/12 to calculate the weekday offset for each month.

XSLT 2.0

You can turn the 1.0 recipe into a function, or use date arithmetic to subtract one day from the first day of the following month. The latter is easier to understand, but the earlier solution is probably faster:

<xsl:function name="ckbk:last-day-of-month" as="xs:integer">
  <xsl:param name="month" as="xs:integer"/>
  <xsl:param name="year" as="xs:integer"/>
  <!--Erster des Monats in angegebenem Jahr -->
  <xsl:variable name="date" select="xs:date(concat(xs:string($year),'-',format-number($month,'00'),'-01'))" as="xs:date"/>
  <xsl:variable name="m" select="xdt:yearMonthDuration('P1M')" as="xdt:yearMonthDuration"/>
  <xsl:variable name="d" select="xdt:dayTimeDuration('P1D')" as="xdt:dayTimeDuration"/>
  <xsl:sequence select="day-from-date(($date + $m) - $d)"/>
</xsl:function>

Discussion

One possible use is constructing calendar pages. The function is fairly easy to understand once you know the leap-year rules. It was ported from Lisp, where each month’s day count is extracted from a list. I chose substring for the same task. You might prefer moving the logic into additional when elements. You could also store data about each month, including its length, in XML.

See also

See recipe Calculate the week number for a given date for methods of storing calendar metadata in XML.

  

 

 

 

back to top