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

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

    To complement the version of Leo Dabus, I added support for projects written Swift and Objective-C, also added support for the optional milliseconds, probably isn't the best but you would get the point:

    Xcode 8 and Swift 3

    extension Date {
        struct Formatter {
            static let iso8601: DateFormatter = {
                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
            }()
        }
    
        var iso8601: String {
            return Formatter.iso8601.string(from: self)
        }
    }
    
    
    extension String {
        var dateFromISO8601: Date? {
            var data = self
            if self.range(of: ".") == nil {
                // Case where the string doesn't contain the optional milliseconds
                data = data.replacingOccurrences(of: "Z", with: ".000000Z")
            }
            return Date.Formatter.iso8601.date(from: data)
        }
    }
    
    
    extension NSString {
        var dateFromISO8601: Date? {
            return (self as String).dateFromISO8601
        }
    }
    

提交回复
热议问题