Swift NSDate ISO 8601 format

后端 未结 3 586
孤独总比滥情好
孤独总比滥情好 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:00

    Your format string was wrong. You indicate a literal Z instead of "Z as zulu time". Remove the single quotes:

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    

    You should always specified the locale as en_US_POSIX when parsing Internet time. This is so commonly overlooked that Apple created the ISO8601DateFormatter class in OS X v10.12 (Sierra).

    0 讨论(0)
  • 2021-01-20 19:12

    You can use NSISO8601DateFormatter or ISO8601DateFormatter for Swift 3.0+

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题