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

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

    If you want to use the ISO8601DateFormatter() with a date from a Rails 4+ JSON feed (and don't need millis of course), you need to set a few options on the formatter for it to work right otherwise the the date(from: string) function will return nil. Here's what I'm using:

    extension Date {
        init(dateString:String) {
            self = Date.iso8601Formatter.date(from: dateString)!
        }
    
        static let iso8601Formatter: ISO8601DateFormatter = {
            let formatter = ISO8601DateFormatter()
            formatter.formatOptions = [.withFullDate,
                                              .withTime,
                                              .withDashSeparatorInDate,
                                              .withColonSeparatorInTime]
            return formatter
        }()
    }
    

    Here's the result of using the options verses not in a playground screenshot:

提交回复
热议问题