Converting UTC date format to local nsdate
Something along the following worked for me in Objective-C :
// create dateFormatter with UTC time formatNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];NSDate *date = [dateFormatter dateFromString:@"2015-04-01T11:42:00"]; // create date from string// change to a readable time format and change to local time zone[dateFormatter setDateFormat:@"EEE, MMM d, yyyy - h:mm a"];[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];NSString *timestamp = [dateFormatter stringFromDate:date];
I keep these two websites handy for converting different time formats:http://www.w3.org/TR/NOTE-datetime
http://benscheirman.com/2010/06/dealing-with-dates-time-zones-in-objective-c/
In Swift it will be:
// create dateFormatter with UTC time format let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone? let date = dateFormatter.date(from: "2015-04-01T11:42:00")// create date from string // change to a readable time format and change to local time zone dateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a" dateFormatter.timeZone = NSTimeZone.local let timeStamp = dateFormatter.string(from: date!)
Try this Swift extension
Swift 4: UTC/GMT ⟺ Local (Current/System)
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) }}// Try itlet utcDate = Date().toGlobalTime()let localDate = utcDate.toLocalTime()print("utcDate - \(utcDate)") //Print UTC Dateprint("localDate - \(localDate)") //Print Local Date
Swift version of c_rath answer:
// create dateFormatter with UTC time formatlet dateFormatter = NSDateFormatter()dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"dateFormatter.timeZone = NSTimeZone(name: "UTC")let date = dateFormatter.dateFromString("2015-04-01T11:42:00")// change to a readable time format and change to local time zonedateFormatter.dateFormat = "EEE, MMM d, yyyy - h:mm a"dateFormatter.timeZone = NSTimeZone.localTimeZone() let timeStamp = dateFormatter.stringFromDate(date!)