![]() |
Table of Contents |
![]() |
Recipe 4.1. Calculating the Day of the WeekProblemGiven the year, month, and day, you want to determine the day of the week. SolutionXSLT 1.0The following calculation does the trick and returns an integer in the range of 0-6, where 0=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.0Use format-date to get the day of the week as a number or a language-dependent string. DiscussionYou will notice that these equations and those in other examples make judicious use of the XPath floor( ) function. This is the only way to emulate integer arithmetic in XSLT 1.0, since all numbers are represented in floating point internally. The reason why this calculation works has to do with intricacies of the Gregorian calendar that are not particularly relevant to XSLT. For example, the fact that 97 leap years occur every 400 years so that every year divisible by 4 is a leap year, except if it is divisible by 100 and not divisible by 400, explains the final calculation. For further information, see Sidebar 1. ![]() |
![]() |
Table of Contents |
![]() |