How to convert UTC date string to local time (systemTimeZone)

19,235

Solution 1

This should do what you need:

NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = @"LLL d, yyyy - HH:mm:ss zzz";
NSDate *utc = [fmt dateFromString:@"June 14, 2012 - 01:00:00 UTC"];
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSLog(@"%@", local);

Note that your example is incorrect: when it's 1 AM on June-14th in UTC, it's still June-13th in EST, 8 PM standard or 9 PM daylight savings time. On my system this program prints

Jun 13, 2012 - 21:00:00 EDT

Solution 2

Swift 3

var dateformat = DateFormatter()
dateformat.dateFormat = "LLL d, yyyy - HH:mm:ss zzz"
var utc: Date? = dateformat.date(fromString: "June 14, 2012 - 01:00:00 UTC")
dateformat.timeZone = TimeZone.current
var local: String = dateformat.string(from: utc)
print(local)


Swift 4: Date Extension UTC or GMT ⟺ Local

//UTC or GMT ⟺ Local 

extension Date {

    // Convert local time to UTC (or GMT)
    func toGlobalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

    // Convert UTC (or GMT) to local time
    func toLocalTime() -> Date {
        let timezone = TimeZone.current
        let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }

}

Solution 3

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MMMM d, yyyy - HH:mm:ss zzz"; // format might need to be modified

NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
[dateFormatter setTimeZone:destinationTimeZone];

NSDate *oldTime = [dateFormatter dateFromString:utcDateString];

NSString *estDateString = [dateFormatter stringFromDate:oldTime];

Solution 4

This convert from GMT to Local Time, you can modify it a bit for UTC Time

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[dateFormatter setTimeZone:gmt]; 
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]]; 
[dateFormatter release];

Taken from iPhone: NSDate convert GMT to local time

Share:
19,235
AAV
Author by

AAV

Updated on June 29, 2022

Comments

  • AAV
    AAV almost 2 years

    Input String: June 14, 2012 - 01:00:00 UTC

    Output Local String: Jun 13, 2012 - 21:00:00 EDT

    I like to get the offset from

    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSLog(@"Time Zone: %@", destinationTimeZone.abbreviation);
    

    Any suggestion ?