XML technologies / XSLT / XSLT Kochbuch / Dates and times / Calculating the week number for a date
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
You want to calculate a date’s week number within the year.
Solution
XSLT 1.0
Week numbers range from 1 to 53. Most years have 52 weeks, but years with 53 Thursdays have 53 weeks.
The solution uses the template with the Julian day:
<xsl:template name="ckbk:calculate-week-number">
<xsl:param name="year"/>
<xsl:param name="month"/>
<xsl:param name="day"/>
<xsl:variable name="ckbk:j-day">
<xsl:call-template name="ckbk:calculate-julian-day">
<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:variable name="d4" select="($j-day + 31741 - ($j-day mod 7)) mod 146097 mod 36524 mod 1461"/>
<xsl:variable name="L" select="floor($d4 div 1460)"/>
<xsl:variable name="d1" select="(($d4 - $L) mod 365) + $L"/>
<xsl:value-of select="floor($d1 div 7) + 1"/>
</xsl:template>Warning!
This function assumes that Monday is the first day of the week. Most other functions in this chapter use the more common convention of weeks starting on Sunday; see the ISO calendar recipes for an explanation of this peculiarity.
XSLT 2.0
Use format-date( ):
<xsl:function name="ckbk:calculate-week-number" as="xs:integer">
<xsl:param name="date" as="xs:date"/>
<xsl:sequence select="xs:integer(format-date($date,'[W]'))"/>
</xsl:function>Discussion
The week number is assigned to each week of a year. Week 1 contains 4 January, equivalently the first Thursday of January. A week spanning the end of one year and the start of the next belongs to the year containing most of its days. This occurs when the year starts on Thursday, or on Wednesday in a leap year. This numbering system is not currently used in the United States.
See also
See the recipe Working with the Islamic calendar.
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