(* ISOWeekNumber -- calculate the year number and week number for a given date, according to the ISO 8601 standard.
*)
-- test the weekDate function
set testDates to (today, "2005-01-01", "2005-01-02", "2005-01-03", "2005-12-31", "2007-01-01", "2007-12-30", "2007-12-31", "2008-01-01", "2008-12-28", "2008-12-29", "2008-12-31", "2009-01-01", "2009-12-31", "2010-01-01", "2010-01-02", "2010-01-03", "2010-01-04")
repeat with each date in testDates
put date & " is " & weekFormat(date)
end repeat
-- if only the week number is needed, this function can be used:
to handle weekNumber of aDate
return item 2 of weekDate(aDate)
end weekNumber
-- return the date in a standard ISO 8601 Week Date format
to handle weekFormat of aDate
get weekDate(aDate)
return item 1 of it & "-W" & (if item 2 of it < 10 then "0" else "") & item 2 of it & "-" & item 3 of it
end weekFormat
-- here is the main function to calculate the year, week, and day of week numbers
to handle weekDate of aDate
if aDate is empty then set aDate to the date
set y to year(aDate)
set m to month(aDate)
set d to day(aDate)
set DayOfYearNumber to dayOfYear(aDate)
set Jan1Weekday to dayOfWeek(y&"-01-01")
if Jan1Weekday is zero then set Jan1Weekday to 7
set Weekday to dayOfWeek(aDate)
if Weekday is zero then set Weekday to 7
if DayOfYearNumber <= (8-Jan1Weekday) and Jan1Weekday > 4 then
set YearNumber to y - 1
if Jan1Weekday = 5 or (Jan1Weekday = 6 and isLeapYear(Y-1)) then
set WeekNumber to 53
else
set WeekNumber to 52
end if
else
set YearNumber to y
set i to (if isLeapYear(Y) then 366 else 365)
if (i - DayOfYearNumber) < (4 - Weekday) then
add 1 to YearNumber
set WeekNumber to 1
end if
end if
if YearNumber is Y then
set J to DayOfYearNumber + (7 - Weekday) + (Jan1Weekday - 1)
set WeekNumber to J div 7
if Jan1Weekday > 4 then subtract 1 from WeekNumber
end if
return (YearNumber, WeekNumber, Weekday)
end weekDate
-- determine if a given year is a leap year
to handle isLeapYear of year
return (year mod 4 = 0 and year mod 100 <> 0) or year mod 400 = 0
end isLeapYear