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

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

    There is a new ISO8601DateFormatter class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.

    Swift 3.0

    extension Date {
        var iso8601: String {
            if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
                return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
            } else {
                var buffer = [CChar](repeating: 0, count: 25)
                var time = time_t(self.timeIntervalSince1970)
                strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
                return String(cString: buffer)
            }
        }
    }
    

提交回复
热议问题