I’m trying to convert a String into a Date object. The String contains a date in this format "Sun, 01 Oct 2023 00:00:00 GMT".
What i did is this:
let formatter = DateFormatter()
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
formatter.timeZone = TimeZone(abbreviation: "UTC")
// dateObject -> Date / StringDate -> String
item.dateObject = item.stringDate?.toDate(formatter: formatter)
// toDate method
extension String {
func toDate(formatter: DateFormatter) -> Date? {
if let dateFromString = formatter.date(from: self) {
return dateFromString
} else {
return nil
}
}
}
But unfortunately item.dateObject is nil. I’ve put a breakpoint in the toDate method and it stops to "return nil". Is the dateFormat correct for that type of date?
Thanks.
>Solution :
The format "E, d MMM yyyy HH:mm:ss Z" is valid for Sun, 01 Oct 2023 00:00:00 GMT
Some notes:
- A two digit day is actually
dd. - Specifying the time zone of the formatter is redundant since it’s part of the time string.
- According to the Unicode specifications the pattern for a three letter zone identifier is lowercase
z. - It’s highly recommended to specify a fixed
Localewhen applying a custom date format.
let timeString = "Sun, 01 Oct 2023 00:00:00 GMT"
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss z"
if let date = formatter.date(from: timeString) {
print(date)
}