Search code examples
iosobjective-cnsdatelocaltime

NSDate always return UTC


I am using NSDateFormatter to convert NSString into NSDate according to local timezone. but it always returns in UTC. I am using this code:

NSString *dateString = @"28-12-2015 04:58:10 PM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
dateFormatter.timeZone = [NSTimeZone localTimeZone];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

In console I am getting this:

Printing description of dateFromString:
2015-12-28 11:28:10 +0000

Please help me to resolve this issue.


Solution

  • Try changing the time zone to GMT

    NSString *dateString = @"28-12-2015 04:58:10 PM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];    
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    dateFromString = [dateFormatter dateFromString:dateString];
    

    In console I got

    2015-12-28 16:58:10 +0000