Search code examples
iosnsdatenscalendar

Something wrong with nscalendar


I can't understand what happening here :( :

NSLog(@"date : %@, hours : %d", self.now, [[self.calendar components:NSHourCalendarUnit fromDate:self.now] hour]);

result

date : 2000-01-01 01:00:19 +0000, hours : 2

Why is it not hours : 1 ? An idea ?

EDIT:

self.calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

and self.now is just a date.


Solution

  • From Apple docs:

    Returns the number of hour units for the receiver.

    - (NSInteger)hour 
    

    Return Value: The number of hour units for the receiver.

    Discussion: This value is interpreted in the context of the calendar with which it is used

    Calendar context makes hour component depending on time zone that set to calendar object.
    When you init calendar by calling
    [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    it automatically retrieve time zone from device settings.

    In log we see GMT+0 time zone (2000-01-01 01:00:19 +0000). I guess your time zone is GMT+1. In this case NSCalendar works correctly.