Parsing a RFC 822 date with NSDateFormatter

后端 未结 4 694
逝去的感伤
逝去的感伤 2021-01-04 03:01

I\'m using a NSDateFormatter to parse a RFC 822 date on the iPhone. However, there is no way to specify optional elements in the date format. There are a couple of optional

4条回答
  •  一向
    一向 (楼主)
    2021-01-04 03:26

    In case this is helpful to anyone else.. here is a NSDate+RFC822String.swift extension based on Simucal's answer.

    It also caches the last used date format that was successful, since setting the dateFormatter.dateFormat is expensive.

    import Foundation
    
    private let dateFormatter: NSDateFormatter = {
        let dateFormatter = NSDateFormatter()
        dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    
        return dateFormatter
    }()
    
    private let dateFormatsWithComma = ["EEE, d MMM yyyy HH:mm:ss zzz", "EEE, d MMM yyyy HH:mm zzz", "EEE, d MMM yyyy HH:mm:ss", "EEE, d MMM yyyy HH:mm"]
    private let dateFormatsWithoutComma = ["d MMM yyyy HH:mm:ss zzz", "d MMM yyyy HH:mm zzz", "d MMM yyyy HH:mm:ss", "d MMM yyyy HH:mm"]
    
    private var lastUsedDateFormatString: String?
    
    extension NSDate {
        class func dateFromRFC822String(RFC822String: String) -> NSDate? {
            let RFC822String = RFC822String.uppercaseString
    
            if lastUsedDateFormatString != nil {
                if let date = dateFormatter.dateFromString(RFC822String) {
                    return date
                }
            }
    
            if RFC822String.containsString(",") {
                for dateFormat in dateFormatsWithComma {
                    dateFormatter.dateFormat = dateFormat
                    if let date = dateFormatter.dateFromString(RFC822String) {
                        lastUsedDateFormatString = dateFormat
                        return date
                    }
                }
            } else {
                for dateFormat in dateFormatsWithoutComma {
                    dateFormatter.dateFormat = dateFormat
                    if let date = dateFormatter.dateFromString(RFC822String) {
                        lastUsedDateFormatString = dateFormat
                        return date
                    }
                }
            }
    
            return nil
        }
    }
    

提交回复
热议问题