iOS Swift 3 : Convert “yyyy-MM-dd'T'HH:mm:ssZ” format string to date object

后端 未结 3 1015
旧巷少年郎
旧巷少年郎 2020-12-05 19:18

Hello i have a dictionary

self.publishedAt = dictionary[\"publishedAt\"] as? NSString

in which i\'m getting date \"2017-01-27T18:36

3条回答
  •  -上瘾入骨i
    2020-12-05 19:55

    To convert string to Date object:

    let string = "2017-01-27T18:36:36Z"
    let isoFormatter = ISO8601DateFormatter()
    let date = isoFormatter.date(from: string)!
    

    Or, if you need to support iOS versions that predate ISO8601DateFormatter:

    let isoFormatter = DateFormatter()
    isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssX"
    isoFormatter.locale = Locale(identifier: "en_US_POSIX")
    isoFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    let date = isoFormatter.date(from: string)!
    

    (To understand why we set the locale for the ISO 8601 date formatter, see Apple Technical Q&A 1480.)

    Then, to convert that to a user-friendly date format, you'd use a separate formatter (or use the second example, above, you can re-use the formatter, but remember to reset the locale back to Locale.current):

    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    let result = formatter.string(from:date)
    

    Note, I'd suggest using those style parameters when presenting the date back to the user rather than the dateFormat string, so it's using the styles appropriate for their locale, rather than assuming they want 24h clock or not and/or whether they use dd-MM-yyyy vs MM-dd-yyyy format.


    Note, changing the formats of date formatter (e.g. changing the dateFormat string) is a relatively expensive process, so if you're performing this process for multiple dates, do not take a single DateFormatter and constantly change its dateFormat or styles repeatedly back and forth (or worse, instantiate new formatters for each date). Instead, create one formatter per date format style and re-use it grammar as much as possible.

提交回复
热议问题