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

后端 未结 12 1908
北恋
北恋 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

    Based on the acceptable answer in an object paradigm

    class ISO8601Format
    {
        let format: ISO8601DateFormatter
    
        init() {
            let format = ISO8601DateFormatter()
            format.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
            format.timeZone = TimeZone(secondsFromGMT: 0)!
            self.format = format
        }
    
        func date(from string: String) -> Date {
            guard let date = format.date(from: string) else { fatalError() }
            return date
        }
    
        func string(from date: Date) -> String { return format.string(from: date) }
    }
    
    
    class ISO8601Time
    {
        let date: Date
        let format = ISO8601Format() //FIXME: Duplication
    
        required init(date: Date) { self.date = date }
    
        convenience init(string: String) {
            let format = ISO8601Format() //FIXME: Duplication
            let date = format.date(from: string)
            self.init(date: date)
        }
    
        func concise() -> String { return format.string(from: date) }
    
        func description() -> String { return date.description(with: .current) }
    }
    

    callsite

    let now = Date()
    let time1 = ISO8601Time(date: now)
    print("time1.concise(): \(time1.concise())")
    print("time1: \(time1.description())")
    
    
    let time2 = ISO8601Time(string: "2020-03-24T23:16:17.661Z")
    print("time2.concise(): \(time2.concise())")
    print("time2: \(time2.description())")
    

提交回复
热议问题