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

后端 未结 12 1720
北恋
北恋 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:23

    Remember to set the locale to en_US_POSIX as described in Technical Q&A1480. In Swift 3:

    let date = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
    print(formatter.string(from: date))
    

    The issue is that if you're on a device which is using a non-Gregorian calendar, the year will not conform to RFC3339/ISO8601 unless you specify the locale as well as the timeZone and dateFormat string.

    Or you can use ISO8601DateFormatter to get you out of the weeds of setting locale and timeZone yourself:

    let date = Date()
    let formatter = ISO8601DateFormatter()
    formatter.formatOptions.insert(.withFractionalSeconds)  // this is only available effective iOS 11 and macOS 10.13
    print(formatter.string(from: date))
    

    For Swift 2 rendition, see previous revision of this answer.

提交回复
热议问题