calendar week (European)

stbi

Member
Licensed User
I was in need of calculating the calendar week for one of my applications. Sounds easy but finally I spent lots of hours the last days ... :sign0148:
There are lots of algorithms and examples on the net, but most of them don't work perfectly :(. The treatment of fractured weeks in the beginning and end of a year can be very complicated. But now I have an algorithm that works (as far as I can tell...)

It covers ISO 8601 standard (and the german DIN 1355 standard), so it should be suitable for most European countries. Calculation rules:
  • Week starts with Monday.
  • The first week must have 4 days in January. In other words: the first week must contain the first Thursday of the year. And January 4.
  • Only years starting or ending with Thursday can have a week #53.

Therefore this algorithm will not work for countries where week starts with Sunday (USA?) or the first week bases on January 1 (UK?). More info and links here: http://en.wikipedia.org/wiki/Week

Cheers,
Stefan
 

Attachments

Cableguy

Expert
Licensed User
I thought that a year only had 52 weeks...always!

I don't understand how it can have #53...

In Portugal, if the last week of the year as only one or two december days the it's numbered as #1
if not is the #52...
I never came across a 53 week calendar!!!:)l
 

stbi

Member
Licensed User
I never came across a 53 week calendar!!!:)l
Cableguy, in Germany the years last always longer ... ;)

Take your PPC, start the calendar, go to the options menue, switch week numbers on. Then go back to the last days of 2004 and switch to week view.

Or have a look here, it's in Portugues.
 

Cableguy

Expert
Licensed User
Ok So then there should be also 51 weeks years, shouldn't?

For instance, 2003 last week has 3 working days, but is still week 1 of 2004

BtW 2004 1st week is kinda of a halfweek as it only has 2 working days...but that me saying :)
 
Last edited:

specci48

Well-Known Member
Licensed User
Hi stbi,

I can estimate the work you have put into this code because I had the same problem some time ago. It put me a knot in my brain.

At last, I got to this solution:
B4X:
Sub GetWeekNumber(ticks)
   currentThursday = GetThursdayOfWeek(ticks)
   firstThursday = GetThursdayOfWeek(DateAdd(0, DateYear(currentThursday) - 1, 0, 3))
   return (currentThursday - firstThursday ) / cTicksPerDay / 7 + 1
End Sub

Sub GetThursdayOfWeek(ticks)
   select DateDayofWeek(ticks)
      case "Monday"
         diff = 3
      case "Tuesday"
         diff = 2
      case "Wednesday"
         diff = 1
      case "Thursday"
         diff = 0
      case "Friday"
         diff = -1
      case "Saturday"
         diff = -2
      case "Sunday"
         diff = -3         
   end select   
   return DateAdd(ticks,0,0,diff)
End Sub

specci48
 

stbi

Member
Licensed User
Hi specci48,

its amazing, but our codes give exactly the same results :sign0098: this makes me feel good :sign0162:

stbi
 
Top