I have an extension on String to convert my date strings to a Date type in Swift 5.2
extension String {
func toDate(withFormat format: String = "MMM d, YYYY HH:mm:ss a") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.timeZone = .current
dateFormatter.dateFormat = format
guard let date = dateFormatter.date(from: self) else {
preconditionFailure("Check the format!!!")
}
return date
}
}
when I try this to convert my date_string is always wrong(check below) :
var sampleDate = "May 5, 2021 1:34:15 AM"
let newDate = sampleDate.toDate()
print(newDate) //prints: "2020-12-28 05:34:15 +0000\n"
My date_string that I want to convert is always in a similar format: "May 5, 2020 9:20 5:39:15 PM"
Any idea what could be wrong? I played around with local, calendar, timezone but did not work! I'm in the US East Coast timezone right now.
Thanks, Cam
Your DateFormatter's dateFormat should be "MMM d, yyyy hh:mm:ss a"
("yyyy" instead of "YYYY" and "hh" instead of "HH")
That works.
Or, as Leo pointed out in the comments, "MMM d, yyyy h:mm:ss a"
(With only one h
) would be better, and it's safer to use
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
(That tells the date formatter not to try to adjust the date format for different local date formatting conventions.)