iOS DateFormatter giving nil ,When device Timezone

2019-08-09 05:30发布

问题:

This question already has an answer here:

  • What is the best way to deal with the NSDateFormatter locale “feechur”? 4 answers
  • DateFormatter doesn't return date for “HH:mm:ss” 1 answer
  • Swift: NSDateFormatter dateFromString returns nil on devices 1 answer

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.