Search code examples
iosobjective-ciphonensdatenstimezone

NSDate show wrong date with NSTimezone


Hi I am trying to display GMT time to my device time. my device time zone is EDT.

I got the GMT time as a string

       // GMT Time-----2014-11-27 19:32:00 

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 dateFormatter.dateFormat = @"HH:mm:ss";
 NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
 NSDate *startDate = [dateFormatter dateFromString:@"2014-11-27 19:32:00"];

I am getting this start date as -

    //startDate---2014-11-27 19:32:00 +0000

Now I am trying to convert this into my local time

NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
dateFormatter2.dateFormat = @"hh:mm a";
NSTimeZone *local = [NSTimeZone localTimeZone];
[dateFormatter2 setTimeZone:[NSTimeZone localTimeZone]];
NSString *startDateStr = [dateFormatter2 stringFromDate:startDate];

As per my timezone(EDT) the result must be - 3:32 PM But I am getting wrong time as

  //startDateStr---02:32 PM

I have printed my timezone difference with GMT

    NSLog(@"TimeZone  %d",[[NSTimeZone localTimeZone] secondsFromGMT]);
   // TimeZone   -14400     - this correct and as per this the startDate must be 03:32 PM

Where I am making the mistake ? Please help me


Solution

  • Very clever. The date that you converted was on January 1st 2000. So daylight savings time was different back then. 19:32 GMT on the 1st of January was 2:32pm in your time zone. But 19:32 GMT today is 3:32pm in your time zone.