Date parseable in Playground, but not in Project

import UIKit

extension String {
  func toDate() -> Date? {
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "MMMM d, yyyy h:mm a"
  dateFormatter.locale = Locale(identifier: "en_US_POSIX")
  dateFormatter.timeZone = .current

  return dateFormatter.date(from: self)
  }
}



let date = "October 3, 2008 7:00 PM".toDate()


Hey guys, I'm getting inconsistent results from the above snippet. Inside of a Playground, it executes just fine and the date parses properly. In a project, the snippet fails and the date winds up nil. Any thoughts on why this could be?

Replies

Tested both in playground and app, works ok:


I get

Optional(2008-10-03 17:00:00 +0000)


in both cases.


Do you test on device or simulator ?

There may be some isues on simulator, if so, test on device.

Try setting the locale before setting the date format string.

Internally, the date format string can be modified based on the locale, so if you set the date format string first the ‘damage’ can already be done before you set the locale.

My guess is that the situations where it fails the user has a override on the 12-/24-hour setting.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"