0

I am trying to convert string to date and then back to string but I always get a fatal error.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss Z" //Your date format
dateFormatter.locale = Locale(identifier: "en_US")
//dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "Tue, 21 Jul 2020 20:04:09 +0000") else {
    fatalError()
}
print(date) //Convert String to Date
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
return newDate

I know there are so many solutions, but none of them are working.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
Noor
  • 2,071
  • 19
  • 28
  • 1
    Change hh (12 hour format) to HH (24 hour format) – Joakim Danielson Jul 21 '20 at 21:17
  • You should set the formatter's locale to "en_US_POSIX" and it should be done before setting the dateFormat – Leo Dabus Jul 22 '20 at 03:01
  • 1
    Btw if your intent is to display the date to the user you should NOT use a fixed date format. You should use dateStyle and respect the user device locale and settings https://stackoverflow.com/questions/28332946/how-do-i-get-the-current-date-in-short-format-in-swift/28347285?r=SearchResults&s=1|21.7619#28347285 – Leo Dabus Jul 22 '20 at 03:03

2 Answers2

2

Try to use this format (HH instead of hh):

dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss Z"
  • hh - "The 12-hour hour padding with a zero if there is only 1 digit"
  • HH - "The 24-hour hour padding with a zero if there is only 1 digit"
pawello2222
  • 46,897
  • 22
  • 145
  • 209
0

if you change from the "20" to "08" then it works, so from "Tue, 21 Jul 2020 20:04:09 +0000" to "Tue, 21 Jul 2020 08:04:09 +0000"

Not sure why, I will play with it more, but I guess it does not like the 24h system.

Jonas