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

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

    Without some manual String masks or TimeFormatters

    import Foundation
    
    struct DateISO: Codable {
        var date: Date
    }
    
    extension Date{
        var isoString: String {
            let encoder = JSONEncoder()
            encoder.dateEncodingStrategy = .iso8601
            guard let data = try? encoder.encode(DateISO(date: self)),
            let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as?  [String: String]
                else { return "" }
            return json?.first?.value ?? ""
        }
    }
    
    let dateString = Date().isoString
    

提交回复
热议问题