How to convert UTC date string to local time (systemTimeZone)
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];
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)
}
}
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