0

i get from json the following format, specifically these are two of the ones I get:

  "createdAt":"2020-09-21T18:24:36.787Z",

  "createdAt":"2020-09-21T18:45:05.250Z",

I used this format:

    lazy var formatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    formatter.timeZone = TimeZone(abbreviation: "UTC+8")
    formatter.locale = Locale.current
    formatter.dateStyle = .medium
    formatter.timeStyle = .none
    return formatter
}()

however, the application only gives me back:

Sep 22, 2020
Sep 22, 2020

why is it not time?

2 Answers2

0

Z in your date string means UTC The "Z" in your dateFormat "yyyy-MM-dd'T'HH:mm:ss.SSSZ" will interprete that as UTC. It doesn't matter which timezone you set your date formatter to. It will only make a difference when getting a string from a Date. Btw You should always set your dateFormatter locale to "en_US_POSIX" before setting the dateFormat when parsing fixed date formats.

Besides that you can not use dateFormat and date/time styles together. It is one or the other.

let formatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = .init(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    return formatter
}()

if let date = formatter.date(from: "2020-09-21T18:24:36.787Z") {
    print(date.description(with: .current))  // Monday, 21 September 2020 15:24:36 Brasilia Standard Time
    let dateString = formatter.string(from: date)
    print("date:", dateString)
}

This will print:

Monday, 21 September 2020 15:24:36 Brasilia Standard Time
date: 2020-09-21T18:24:36.787+0000


If you need to display a localized date to the user check this post

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

Two options for building and parsing ISO 8601/RFC 3339 date/time strings:

  1. Use DateFormatter with no “styles”, but specify X for the timezone:

    let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
        return formatter
    }()
    

    Ironically, note the X rather than Z, to make sure that when you are building strings from dates, that the timezone is shown as Z rather +0000.

  2. Use ISO8601DateFormatter:

    let formatter: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions.insert(.withFractionalSeconds)
        return formatter
    }()
    
Rob
  • 415,655
  • 72
  • 787
  • 1,044