iOS DateFormatter giving nil ,When device Timezone and region changes [duplicate]

久未见 提交于 2019-12-11 12:04:21

问题


I have a date in string like this

let time = "Wed Oct 10 12:22:32 UTC 2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EE MM dd HH:mm:ss zz yyyy"
let rawDate = dateFormatter.date(from: time) // GETTING rawDate
dateFormatter.dateFormat = "d MMM yyyy, h:mm a"
guard let date = rawDate else { return "" } // rawDate NIL HERE
let time = dateFormatter.string(from: date)

It works fine in my timezone Mumbai and region India. But when i'm changing it to some other region and timezone, rawDate is getting nil.

What's wrong i'm doing?

P.S: Please give a generic answer, No fixed timezone or Locale is needed.

Update: As the duplicate reference consist en_US posfix, This doesn't make code generic, if I use en_GB or something else the data will be incorrect.

来源:https://stackoverflow.com/questions/52741294/ios-dateformatter-giving-nil-when-device-timezone-and-region-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!