问题
I'm trying to get a date from a string with multiple time zones, It works without any problems if the API returns zones with abbreviations like CST
or UTC
but it fails if it returns EET
let timeString = "17:32 (EET)"
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm (zzz)"
let time = formatter.date(from: timeString) // return nil
Any idea what is the issue might be?!
回答1:
Probably because there is more than one timezone that matches the timezone abbreviation or the date formatter's default date (January 1st) doesn't match the daylight savings of the timezone abbreviation used. Not all countries uses daylight savings time as well it might change at any time. Check this link. This will probably happen for all non US timezones abbreviation as well. For example CST
it is used for "China Standard Time"
and "Chicago Standard Time"
as well. You can workaround that issue setting your date formatter property isLenient
to true. Note that this will result in a date of January 1st 2000 with a probably incorrect timezone offset. If you have control of your string input you should use the timezone identifiers instead of its abbreviations to avoid ambiguity. You should also set your date formatter's locale to "en_US_POSIX"
when parsing fixed date format to avoid date formatter's reflecting the users device locale and settings:
let timeString = "17:32 (EET)"
let formatter = DateFormatter()
formatter.locale = .init(identifier: "en_US_POSIX")
formatter.dateFormat = "HH:mm (zzz)"
formatter.isLenient = true
let date = formatter.date(from: timeString) // "Jan 1, 2000 at 1:32 PM" "BRT Brazilian Standard Time"
So you should use "GMT+2"
or "GMT-3"
to avoid ambiguity or as I have already suggested use its identifiers "HH:mm (VV)"
i.e. "Europe/Athens"
or "America/Sao_Paulo"
来源:https://stackoverflow.com/questions/60364808/timezone-date-formatting-issue