Search code examples
iosnsdatenstimezone

Confusion with NSDate


I am trying trying to get a create an object of NSDate this way

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   // [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit  | NSMinuteCalendarUnit)fromDate:[NSDate date]];
    NSInteger day    = [weekdayComponents day];
    NSInteger month  = [weekdayComponents month];
    NSInteger year   = [weekdayComponents year];


    NSDateComponents *timeZoneComps=[[NSDateComponents alloc] init];
    [timeZoneComps setDay:day];
    [timeZoneComps setMonth:month];
    [timeZoneComps setYear:year];
    [timeZoneComps setHour:00];
    [timeZoneComps setMinute:00];
    [timeZoneComps setSecond:01];

    m_currentDate         = [gregorian dateFromComponents:timeZoneComps];

When I log the currentDate, I get this

"2014-07-07 06:00:01 +0000"

If I save this to plist I get this

07-Jul-2014 11:30:01 am

If I use "UTC" as the time zone

I get it as

"2014-07-07 00:00:01 +0000"

and inside plist it shows as

07-Jul-2014 5:30:01 am

I am not understanding what is going on, Can anybody help me out with this

I want to know, if I dont set any timeZone what timeZone will be used?

Do we need to explicitly set UTC as timeZone or we need to use systemTimeZone.


Solution

  • The thing you need to realise about NSDate is that there is no such thing as day, week, month, year, timezone, etc...

    An NSDate is purely a point in time. It has no information about what time zone it is etc...

    Effectively it is just a number. You can think of it as using UTC if that helps.

    The classes that give you things like time zone are NSCalendar, NSDateFormatter, etc...

    I'm guessing you're in a timezone of UTC+6? Thats why when you create a date with 00:00:01 and you log it out then it displays as 06:00:01.

    This is nothing to do with the NSDate. What you are seeing in the console is a string. It is a representation of the date object using the default time zone (your own).

    I'd have to see you code for saving to a plist but I suspect this is the same problem. You are saving something and assuming it is using a particular time zone when in reality it isn't.