Determining the Last Day of the Month
Problem
Given a month and a year, determine the last day of the month.
Solution
<xsl:template name="date: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>
Discussion
This function has potential application for constructing pages of a
calendar. It is simple enough to understand once you know the rules
governing a leap year. This function was translated from Lisp, in
which the number of days in each month was extracted from a list. I
choose to use substring to accomplish the same task. You may prefer
to place the logic in additional when
elements.
You might also store data about each month, including its length, in
XML.
See Also
See Recipe 3.5 for ways to store calendar metadata in XML.
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.