ISO8601 WeekOfYear() function

Share your advanced knowledge/code with the community.
mahan
Posts: 19
Joined: Sun Nov 15, 2015 9:44 pm

ISO8601 WeekOfYear() function

Post by mahan »

The WeekOfYear() function is a complement to the existing Date()-functions in the library.

In some regions, such as the Nordics, the week of the year (or more commonly referred to as just the 'week') is widely used for time planning.

Link to more info: https://en.wikipedia.org/wiki/ISO_week_date

Function + Demo code:

Code: Select all

EnableExplicit

;Credit for original code:
;http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
Procedure WeekOfYear(d.i)
  !var d = new Date(v_d*1000)
  !var target  = new Date(d.valueOf());  
  !var dayNr   = (d.getDay() + 6) % 7;  
  !target.setDate(target.getDate() - dayNr + 3);  
  !var firstThursday = target.valueOf();  
  !target.setMonth(0, 1);  
  !if (target.getDay() != 4) {  
  !    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);  
  !}  
  !return 1 + Math.ceil((firstThursday - target) / 604800000);
EndProcedure


Procedure main()
  Debug "WeekOfYear(Date()) = " + WeekOfYear(Date())
  Protected yearDayCounter.i
  Protected yearDayDate.f = Date(Year(Date()), 1, 1, 0, 0, 0)
  For yearDayCounter = 1 To 365
    Debug "WeekOfYear('" + FormatDate("%yyyy-%mm-%dd", yearDayDate) + "') = " + WeekOfYear(yearDayDate) 
    yearDayDate+(60*60*24) ; advance 1 day
  Next
EndProcedure

main()