How to Convert date into local time zone ios swift
I hope this will work for your problem
func serverToLocal(date:String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date!)
return date
}
If you want the result to be a Date object just use the first part of @Intellij-Shivam's answer:
func serverToLocal(date:String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let localDate = dateFormatter.date(from: date)
return localDate
}
(note that DateFormatter.date(from:)
returns an optional, which is correct because the input date string might not be in the correct format.)
There is no such thing as a Date
in your local time zone. Dates
don't have a time zone. They record an instant in time all over the planet.
To display a date in your local time zone you can use the DateFormatter
class method localizedString()
:
let dateString = DateFormatter.localizedString(
inputDate,
dateStyle: .medium,
timeStyle: .medium)