1. To convert UTC(Coordinated Universal Time) to Local timezone
func convertToLocalDateFromUTCDate(dateStr : String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
let sourceDate = formatter.date(from: dateStr)
let formatter2 = DateFormatter()
formatter2.dateFormat = "MMM dd @hh:mm aa"
let localTime = formatter2.string(from: sourceDate!)
print("local time %@",localTime)
return localTime
}
2.To convert Local timezone to UTC(Coordinated Universal Time)
func convertToUTCFromLocalDate(dateStr : String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = "MMM dd @hh:mm aa"
let utc = NSTimeZone(abbreviation: "UTC")
formatter.timeZone = utc as TimeZone!
formatter.dateFormat = "MMM dd @hh:mm aa"
let localDate: Date? = formatter.date(from: dateStr)
let timeZoneOffset: TimeInterval = TimeInterval(NSTimeZone.default.secondsFromGMT())
let utcTimeInterval: TimeInterval? = (localDate?.timeIntervalSinceReferenceDate)! - timeZoneOffset
let utcCurrentDate = Date(timeIntervalSinceReferenceDate: utcTimeInterval!)
print(UTC time %@",utcCurrentDate)
return formatter.string(from: utcCurrentDate)
}
0 Comment(s)