cole
cole

Reputation: 1273

Swift JSON dates

What would be most efficient way to handle and format different date strings returned from the same JSON object. The API I'm using returns either 2021-02-08T21:00-08:00 or 2021-02-09T06:00+01:00 etc, based on location. The API also includes a timezone string which may be handy - Europe/London

Previous code before noticing the API includes different strings.

func timeFormat(date: String) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm-ss:SSS"
    ///formatter.dateFormat = "yyyy-MM-dd'T'HH:mm+ss:SSS"
    let formattedDate = formatter.date(from: date) ?? Date()
    formatter.dateFormat = "h a"
    return formatter.string(from: formattedDate)
}

UPDATE

As @gcharita and @JoakimDanielson pointed out my string was the same but I accidentally formatted it incorrectly. Now it's working fine. My mistake and take full credit for it.

func timeFormat(date: String) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mmZZZZZ"
    let formattedDate = formatter.date(from: date) ?? Date()
    formatter.dateFormat = "h a"
    return formatter.string(from: formattedDate)
}

Upvotes: 1

Views: 117

Answers (2)

Patru
Patru

Reputation: 4551

Since you only have to deal with one date format (as previous posters mentioned) you should leave this to the JSONDecoder and simply define the dateDecodingStrategy like this:

let decoder = JSONDecoder()
let dateFormatter = DateFormatter()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mmZZZZZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)

Now your decoder will happily convert all dates that match the given format. Much easier than dealing with all the messy formats yourself.

Upvotes: 1

gcharita
gcharita

Reputation: 8337

The -08:00 and +01:00 of the example dates are not seconds and milliseconds as you specify in your date format. ("yyyy-MM-dd'T'HH:mm-ss:SSS" and "yyyy-MM-dd'T'HH:mm+ss:SSS") This is the ISO 8601 time zone format.

As @JoakimDanielson mentioned in the comments, both dates have the same format which apparently is: yyyy-MM-dd'T'HH:mmZZZZZ

Upvotes: 1

Related Questions