Search code examples
iosobjective-cnsdatensdateformatternstimezone

Objective-c : How to convert PST to UTC/local time zone


Am getting time stamp from server as "2015-11-12T03:54:52Z" which is in PST. I want to convert this string to UTC/Local time zone format. I tried in the following way

NSDateFormatter *pstFormatter = [[NSDateFormatter alloc] init];
[pstFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
[pstFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *pstQUU = [pstFormatter dateFromString:@"2015-11-12T04:03:03Z"];

Original output : 2015-11-12 04:03:03 +0000
Expected output : 2015-11-12 12:03:03 +0000 (UTC)

Solution

  • Try adding the UTC offset values like this

        NSDateFormatter *pstFormatter = [[NSDateFormatter alloc] init];
        NSTimeZone *pstTimezone = [NSTimeZone timeZoneWithName:@"America/Los_Angeles"];
        [pstFormatter setTimeZone:pstTimezone];
        [pstFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
        NSDate *pstDate = [pstFormatter dateFromString:@"2015-11-12T04:03:03Z"];
    
        NSTimeInterval utcSeconds = [pstDate timeIntervalSince1970] - [pstTimezone secondsFromGMT];
        NSDate *utcDate = [NSDate dateWithTimeIntervalSince1970:utcSeconds];