Search code examples
iosobjective-cnsdateformatter

Convert UTC to CST in NSDateFormatter


I am getting the following string to be used, but it is from UTC-0, and I need to convert it to CST.

serverdate = @ "2017-07-31 02:18:50";

I added the following code, but it returns nil

NSDateFormatter *dfLocal = [[NSDateFormatter alloc] init];
[dfLocal setDateFormat:@"yyyy-MM-dd HH:mm"];
[dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"CST"]];

NSString *time =[dfLocal stringFromDate:serverdate];
NSLog(@"%@", time);

I even tried the following options, no luck.. still it returns nil.

[dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"CDT"]];

and tried

[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"America/Chicago"]];

Solution

  • First you need to handle the seconds in your time:

    [dfLocal setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    Next set the timezone to UTC and convert your string:

    [dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    NSDate *serverUTC = [dfLocal dateFromString:serverdate];
    

    Now change the time zone and convert back to a string:

    [dfLocal setTimeZone:[NSTimeZone timeZoneWithName:@"America/Chicago"]];
    NSString *time =[dfLocal stringFromDate:serverUTC];
    

    Use America/Chicago as that will handle DST correctly.

    HTH