-1

I know that this topic is fully discussed here and in other forums. Unfortunately, I still cannot understand why the Date is nil.

Note that when I run the code in the Debugger or in Playground then it works totally fine. It's something to do with the fact that it runs on the device.

   var dateString = "2019-12-17 3:48:02 PM"
   let dateFormatter = DateFormatter()
   dateFormatter.locale = Locale.current
   dateFormatter.timeZone = TimeZone.current
   dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss a"
   let date = dateFormatter.date(from: dateString) // date is nil
Nativ
  • 3,092
  • 6
  • 38
  • 69
  • 1
    The 12 hour format is hh, not HH. See also https://stackoverflow.com/q/40692378/1187415 – Martin R Dec 17 '19 at 16:15
  • 1
    Try setting Locale to something that you know supports AM/PM, like "en_US_POSIX" or "en_GB" etc – Joakim Danielson Dec 17 '19 at 16:15
  • Thanks for the reply guys, @MartinR I actually tried it with both HH and hh but it didn't work. I set it up to hh anyway since I'm using 12-hour clock. – Nativ Dec 18 '19 at 08:26

1 Answers1

0

Add en_US as your Locale, like this:

dateFormatter.locale =  NSLocale(localeIdentifier: "en_US")
Marina Aguilar
  • 1,151
  • 9
  • 26