How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

后端 未结 12 1743
北恋
北恋 2020-11-21 22:43

How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339?

The goal is a string that looks like this:

\"2015-01-01T00:0         


        
12条回答
  •  忘掉有多难
    2020-11-21 23:41

    Uses ISO8601DateFormatter on iOS10 or newer.

    Uses DateFormatter on iOS9 or older.

    Swift 4

    protocol DateFormatterProtocol {
        func string(from date: Date) -> String
        func date(from string: String) -> Date?
    }
    
    extension DateFormatter: DateFormatterProtocol {}
    
    @available(iOS 10.0, *)
    extension ISO8601DateFormatter: DateFormatterProtocol {}
    
    struct DateFormatterShared {
        static let iso8601: DateFormatterProtocol = {
            if #available(iOS 10, *) {
                return ISO8601DateFormatter()
            } else {
                // iOS 9
                let formatter = DateFormatter()
                formatter.calendar = Calendar(identifier: .iso8601)
                formatter.locale = Locale(identifier: "en_US_POSIX")
                formatter.timeZone = TimeZone(secondsFromGMT: 0)
                formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
                return formatter
            }
        }()
    }
    

提交回复
热议问题