Adrian Nier Code

Back to overview

Week number

Last modification: Monday, August 25, 2008 12:47 am

Returns the week number of the specified date.

Function Calls

weekNumber(current date)
 

Implementation

on weekNumber(_dateObject)
   
   
   script Week_Number_Extras
      
      -- Define an extra function to calculate how many days of a week belong to the next year
      on daysBelongingToNextYear(_dateObject)
         -- Find out how many of the next 6 days belong to the next year
         set _currentYear to year of _dateObject
         
         set _daysInNextYear to 0
         repeat with _dayOffset from 0 to 6
            if (year of (_dateObject + (_dayOffset * (24 * 60 * 60)))) ≠ _currentYear then
               set _daysInNextYear to _daysInNextYear + 1
            end if
         end repeat
         
         return _daysInNextYear
         
      end daysBelongingToNextYear
      
   end script
   
   -- Make a copy of the passed date object to avoid changes to the original
   copy _dateObject to _dateObjCopy
   
   -- Save the year for later
   set _yearOfGivenDate to year of _dateObjCopy
   
   -- Set the date back to a Monday
   repeat
      if weekday of _dateObjCopy is Monday then exit repeat
      set _dateObjCopy to _dateObjCopy - (24 * 60 * 60)
   end repeat
   
   -- Find out how many days of this week belong to the next year
   -- If at least 4 days do belong to next year then
   -- it’s safe to assume that it’s the first week of the year
   tell Week_Number_Extras to set _daysBelongingToNextYear to daysBelongingToNextYear(_dateObjCopy)
   if _daysBelongingToNextYear ≥ 4 then return 1
   
   -- Set the date back a week at a time until the previous year is reached
   -- Count how many weeks had to pass to reach the previous year
   set _weeksPassed to 0
   repeat
      if year of _dateObjCopy ≠ _yearOfGivenDate then exit repeat
      set _dateObjCopy to _dateObjCopy - (7 * 24 * 60 * 60)
      set _weeksPassed to _weeksPassed + 1
   end repeat
   
   -- Return the week number depending on wether the last monday of the previous year
   -- did belong to the first week of this year or not
   tell Week_Number_Extras to set _daysBelongingToNextYear to daysBelongingToNextYear(_dateObjCopy)
   if _daysBelongingToNextYear ≥ 4 then
      return _weeksPassed + 1
   else
      return _weeksPassed
   end if
   
end weekNumber