Search code examples
swiftnsdateformatterdate-formattingdateformatter

How to convert a slightly misformed RFC822 string to a date?


One of my sources contains date strings like this:

Fri, 22 May 2020 22:49:06+5:30

This looks like an RFC 822 date, except for the last timezone part.

I tried to convert this string to a date with code like this:

let str = "Fri, 22 May 2020 22:49:06+5:30"

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ssZ"

let date = formatter.date(from: str)

I tried all sorts of dateFormat strings, but the last line keeps returning nil.

Is there any way to convert this example string to a valid date by using a DateFormatter?


Solution

  • The problem is the missing leading zero in the time zone part, there is no corresponding symbol.

    A possible solution is to insert the missing zero with Regular Expression

    let str = "Fri, 22 May 2020 22:49:06+5:30"
    let adjustedString = str.replacingOccurrences(of: "([+-])(\\d:\\d{2})", with: "$10$2", options: .regularExpression)
    
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ssZ"
    
    let date = formatter.date(from: adjustedString)