XML technologies / XSLT / XSLT Kochbuch / Dates and times / Calculating the day of the week
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
You want to determine the day of the week from a given year, month and day.
Solution
XSLT 1.0
The following calculation does this and returns an integer from 0 to 6, where 0 denotes Sunday.
<xsl:template name="ckbk:calculate-day-of-the-week">
<xsl:param name="date-time"/>
<xsl:param name="date" select="substring-before($date-time,'T')"/>
<xsl:param name="year" select="substring-before($date,'-')"/>
<xsl:param name="month" select="substring-before(substring-after($date,'-'),'-')"/>
<xsl:param name="day" select="substring-after(substring-after($date,'-'),'-')"/>
<xsl:variable name="a" select="floor((14 - $month) div 12)"/>
<xsl:variable name="y" select="$year - $a"/>
<xsl:variable name="m" select="$month + 12 * $a - 2"/>
<xsl:value-of select="($day + $y + floor($y div 4) - floor($y div 100) + floor($y div 400) + floor((31 * $m) div 12)) mod 7"/>
</xsl:template>XSLT 2.0
Use format-date, to obtain the day of the week as a number or as a language-dependent string.
Discussion
You will notice that these equations, like those in the other examples, make good use of the XPath function floor(). This is the only way to emulate integer arithmetic in XSLT 1.0 because all numbers are represented internally as floating-point values. This calculation works because of subtleties of the Gregorian calendar that are not particularly relevant to XSLT. For example, the final calculation follows from there being 97 leap years in 400 years: every year divisible by 4 is a leap year unless it is divisible by 100 but not by 400. For more information, see the section The logic behind the calculations in the next recipe.
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 terms as the printed edition: the work and all its parts are protected by copyright. All rights are 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