0

I am receiving date in string form from server and I need to show the date according to my time zone (Indian: GMT +5:30). Here is my code

NSString *dateString = @"2015-08-10 11:45:10";

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    //Create the date assuming the given string is in GMT
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    NSDate *date = [dateFormatter dateFromString:dateString];

    NSLog(@"%@",date);

    NSLog(@"%@",[dateFormatter stringFromDate:date]);

    //Create a date string in the local timezone
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
    NSString *localDateString = [dateFormatter stringFromDate:date];
    NSLog(@"date = %@", localDateString);

    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];

    [dateFormatter2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];

    NSDate *date2 = [dateFormatter2 dateFromString:localDateString];

    NSLog(@"%@",date);

And the Log is:

2015-08-10 11:45:10 +0000 (NSDate)
2015-08-10 11:45:10 (NSString)
date = 2015-08-10 17:15:10 (NSString)
2015-08-10 11:45:10 +0000 (NSDate)

My issue is with last log (2015-08-10 11:45:10 +0000) Why it is not 2015-08-10 17:15:10??

Developer
  • 6,375
  • 12
  • 58
  • 92

1 Answers1

0

The last line prints what it does because you're printing an NSDate, and NSDate does not have a time zone. It literally has no attribute or internal state that indicates a time zone. Time zones exist only for presenting data to users, commonly as you're doing via NSDateFormatter. But if you log the value of an NSDate you'll get a GMT string, since the NSDate itself has no time zone.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170