I have received date-time as String from server. I am unable to parse Date if date time is exact time of daylight saving time happen. How to handle when date-time string is "2022-03-13T02:00:00.000000"
Output:
2022-03-13 05:00:00 0000
2022-03-13 06:59:00 0000
failed
2022-03-13 07:00:00 0000
2022-03-13 08:00:00 0000
Code:
extension String {
func date(using format: String) {
let df = DateFormatter()
df.dateFormat = format
df.timeZone = .current
if let date = df.date(from: self) {
print(date)
}
else {
print("failed")
}
}
}
"2022-03-13T00:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T01:59:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T02:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T03:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
"2022-03-13T04:00:00.000000".date(using: "yyyy-MM-dd'T'HH:mm:ss.SSSSSS")
CodePudding user response:
You just need to set your date formatter's calendar property. This will also avoid using the user device's calendar which might result in parsing the wrong year. Don't forget to always set your date formatter's locale to "en_US_POSIX" when parsing a fixed date format:
extension String {
func date(using format: String) -> Date? {
let df = DateFormatter()
df.calendar = .init(identifier: .iso8601)
df.locale = .init(identifier: "en_US_POSIX")
df.timeZone = .current
df.dateFormat = format
df.date(from: self)
}
}
Note also that this approach will create a new date formatter every time you call this method. You should avoid that as well creating a static formatter. I would also make sure if the date string is using the current timezone. Usually it is UTC timezone.
CodePudding user response:
Adopt the ISO8601DateFormatter
To convert those strings into dates, then when you need to display them into your app use a date formatter set to the desired time zone.
In this way you won’t have any trouble with daylight savings conversions.
Of course when you need to re-encode a date into a String
For transmitting it use again the ISO8601DateFormatter
In order to keep the same format used for receiving them.