0

I use the following code to convert a string into a date:

// Input is "06-10-18, 01:30 pm"

func convertStringToDate(string: String) -> Date {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM-yyyy, hh:mm a"
    return formatter.date(from: string)!
}

This works fine on simulators and my devices, however it crashes on return for a couple of client devices.

I tried seeing what was wrong by making it return a string from a date, and on the client devices it returns this:

"06-10-18, 13:30"

Why is it returning differently on a handful of devices?

  • Possible duplicate of https://stackoverflow.com/questions/40692378/dateformatter-doesnt-return-date-for-hhmmss/ : set the formatter‘s locale to Posix. – Martin R Oct 06 '18 at 07:28

1 Answers1

0

The returned date is correct, you can check that using the .timeIntervalSince1970 property. What happens is that when you print the date (which is actually just a TimeInterval, aka Double, a specific point in time, independent of any calendar or time zone), it's printing its description property, with the current device settings.

To print a date using your current locale, use this instance method:

let date = convertStringToDate(string: "06-10-18, 01:30 pm")
print(date.description(with: Locale(identifier: "en_US_POSIX")))
ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • Would this also apply using 'en_GB' and other locales? –  Oct 06 '18 at 09:56
  • 1
    Yes of course, you choose the locale. It would only change the string representing the date. But as a `Date`, it is still the same number (timeIntervalSince1970) – ielyamani Oct 06 '18 at 09:58