1

So when extracting the dates components from NSDate object using NSCalendar and NSDateComponents I encountered a weird behavior. If the date is 0 sec from 1970 the week component will return 53. Is there an explination for this or a way to fix other than the obvious way of modulus 52?

here is the code you can run on your machine to test:

-

 (void)testDate {
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:0];
    NSDateComponents *comp = [cal components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSWeekCalendarUnit) fromDate:date];
    DLog(@"%d/%d/%d week: %d", [comp day],[comp month], [comp year], [comp week]);

}

and here is the output:

31/12/1969 week: 53
(gdb) po date
1970-01-01 00:00:00 +0000
(gdb) 
Edward Ashak
  • 2,411
  • 2
  • 23
  • 38

2 Answers2

1

Well I got this,

2011-06-22 22:38:50.516 SmallTasks[23164:903] 1/1/1970 week: 1

So I am bit surprised by the result you got but I am not that surprised that a week: 53 turned up as 52 * 7 = 364 and we've 365 days in a year. For that to happen I would expect the week to start on Sunday on 1969 but it didn't.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
  • I had similar results, I got week 1 as well, but I got 31/12/1979 but that is only because my local time zone is -0500. – Joe Jun 22 '11 at 17:23
  • After reading more about it m not surprised about the week 53 but still checking to see why did i get the components one day back – Edward Ashak Jun 22 '11 at 18:56
0

You my friend have discovered the leap week. I have run across this doing some SQL reporting a couple years back.

Joe
  • 56,979
  • 9
  • 128
  • 135
  • I must say that I am not sure why 1969 would have a leap week. The reason why it is printing 31/12/1969 on the other hand is because you are in a - timezone. – Joe Jun 22 '11 at 16:18
  • I didnt add any timezone calculations the code above is exactly what ran no the debugger and the weird thing is that the components go back one day and week points forward to the relative week of the 1969 year – Edward Ashak Jun 22 '11 at 16:25
  • So how to do you deal with leap week/years then ? – Edward Ashak Jun 22 '11 at 16:28
  • What are your intentions? When I ran the code though I got week 1. 1969 should not have 53 weeks. While 53 weeks is possible it is used by a variant of the Gregorian calendar and the code you posted should show week 1. – Joe Jun 22 '11 at 16:33
  • @joe 1969 was not a leap year by the way 1960, 1964, 1968 were leap years – Edward Ashak Jun 22 '11 at 16:35
  • By the way, this is an excellent explanation on how to determine week 52-53 years. http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm – Edward Ashak Jun 22 '11 at 17:13