Swift NSDate ISO 8601 format

后端 未结 3 707
孤独总比滥情好
孤独总比滥情好 2021-01-20 18:54

I am working on date formats in Swift and am trying to convert a string date to NSDate and an NSSate to string date (ISO 8601 format).

This is my code



        
3条回答
  •  遇见更好的自我
    2021-01-20 19:19

    If you're targeting iOS 11.0+ / macOS v10.13+ (High Sierra), you can simply use ISO8601DateFormatter with the withInternetDateTime and withFractionalSeconds options, like so:

    let stringDate = "2016-05-14T09:30:00.000Z" // ISO 8601 format
    
    let iso8601DateFormatter = ISO8601DateFormatter()
    iso8601DateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
    let date = iso8601DateFormatter.date(from: stringDate)
    
    print("Date = \(date)") // Output is 2016-05-14 09:30:00 +0000
    

    For working with DateFormatter on older systems, see Apple Tech Note QA1480:

    if you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not), and between machines ("en_US_POSIX" works the same on iOS as it does on OS X, and as it it does on other platforms).

    Here is a snippet of Swift 5, based on the sample code provided:

    let stringDate = "2016-05-14T09:30:00.000Z" // ISO 8601 format
    
    let rfc3339DateFormatter = DateFormatter()
    rfc3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
    rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
    rfc3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    let date = rfc3339DateFormatter.date(from: stringDate)
    
    print("Date = \(date)") // Output is 2016-05-14 09:30:00 +0000
    

提交回复
热议问题