1

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.

Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69
  • Is `rawDate` nil because the format is wrong? You are not using `"d MMM yyyy, h:mm a"` to parse the time string. – Stephen O'Connor Oct 10 '18 at 13:32
  • @rmaddy: Please read question again, your duplicate ref. consist hard coded idenfiers, which i don't need. – Abhishek Thapliyal Oct 10 '18 at 13:33
  • @SteveO'Connor: U r wrong, first we need to convert in same format in which string date is. Then apply custom date format. – Abhishek Thapliyal Oct 10 '18 at 13:35
  • @rmaddy: Either provide me generic answer which will work in every region, or reopen my question, so that some one help me. – Abhishek Thapliyal Oct 10 '18 at 13:46
  • @vadian: Please help me here – Abhishek Thapliyal Oct 10 '18 at 13:48
  • 4
    Yes, you need a hardcoded locale of `en_US_POSIX`. This is required when parsing a fixed format date string. You can't expect a string with English names in it to be parsed in a non-English locale. And this special locale also deals with various user preferences such as 12/24-hour setting. Please read the duplicate and its answers. This is only needed when creating a `Date` from a `String`, not the other way around. – rmaddy Oct 10 '18 at 13:51
  • @rmaddy: Can move this comment to answer so that it will be more helpful. – Abhishek Thapliyal Oct 10 '18 at 13:57
  • 2
    I added more duplicates. No need to reopen this one and post an answer that you will find already in the duplicates. – rmaddy Oct 10 '18 at 14:06

0 Answers0