brandonscript
brandonscript

Reputation: 72885

NSDateFormatter format to parse long-form date with '(UTC)' (from MIME header)

I'm trying to parse some dates from old email messages' MIME headers:

"Sun, 31 Aug 2008 23:38:35 +0000 (UTC)"

Because there are a bunch of different ones, I'm creating date formatter strings in a loop. Unfortunately none of these are capturing this one, though, and I don't know why?

let date = "Sun, 31 Aug 2008 23:38:35 +0000 (UTC)"

extension String {
    func toDate() -> Date? {

        var date: Date?
        let dateFormatter = DateFormatter()
        let formats = [
            "yyyy-MM-dd HH:mm:ss",
            "E, d MMM yyyy HH:mm:ss Z",
            "E, d MMM yyyy HH:mm:ss Z (z)",
            "E, d MMM yyyy HH:mm:ss",
            "yyyy-MM-dd'T'HH:mm:ssZ"
        ]
        formats.forEach { (format) in
            dateFormatter.dateFormat = format
            if let parsed = dateFormatter.date(from: self) {
                date = parsed
            } else {
                print(":(")
            }
        }

        return date
    }
}

date.toDate()

Upvotes: 0

Views: 70

Answers (1)

rmaddy
rmaddy

Reputation: 318814

The format "E, d MMM yyyy HH:mm:ss Z (z)" works for "Sun, 31 Aug 2008 23:38:35 +0000 (UTC)". But it will only work if the user's locale is set to English. When parsing fixed format date strings, be sure you set the date formatter's locale to en_US_POSIX:

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

This not only ensure it properly handles the English weekday and month names, it also avoids issues if the user has changes the 12/24-hour time setting on their device.

Upvotes: 1

Related Questions