I'm working on date formatter, I got a response of date from server in string type, which I convert into date format but what I want to do is to convert a date and then manage according to local time.
For example, if 12/06/2017, 06:48:03
is a date from server and i'm from Pakistan so it gives me a date and time according to GMT+5 which is 12/06/2017, 11:48:03
Same as from India it gives me a date and time according to GMT+5:30 which is 12/06/2017, 12:18:03
Here is a source code
public class func converServerTimeStampToDate (_ timeStamp: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let localDate = dateFormatter.date(from: timeStamp)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "MM/dd/yyyy, hh:mm:ss a"
// return dateFormatter.string(from: localDate!)
return dateFormatter.date(from:dateFormatter.string(from:
localDate!))!
}
Any help would be appreciated !!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With