Hoping someone can help me with this json data

Hi everyone. I built a cheesy mega millions app that a user can get random numbers from every time they click a button. Its pretty basic but I am new to this and wanted to try something on my own. There is a silly story as to why I had this for an idea to build but that’s for another time.

Another thing the app does is it connects to an api which has information about every drawing all the way back to 2002.

On to the question… the api gives json data and one of the variables is a date. My problem is that the date comes back as a string and looks like this “2021-06-25T00:00:00.000”.

My entire app works including the date but I can’t figure out how to change that into a better readable form like " 06/25/2021 " or even anything similar to a human readable form lol. I found some easy ways to format Date() but this is coming to me as a string and not a date.

I am hoping someone here is super smarter than I am and can help me.

Thanks in advance. Let me know if you need more information.

Dates in JSON are represented with strings. The trick is to figure out what format the string is in and then set your dateDecodingStrategy accordingly.

For the example you give, set the dateDecodingstrategy on your decoder to .iso8601. This will give you a Date object you can then format however you need to in order to display it to the user.

1 Like

Thanks so much for your response. I misunderstood what was actually happening until I thought about what you were telling me. I still had a lot more research to do because the format wouldn’t accept .iso8601. It wasn’t exactly the same, so I was getting a corrupted data error. So after hours of google I found something that fixed my code. I just had to change the format to what I was receiving. This is the code I had to use…

// "draw_date":"2021-06-25T00:00:00.000"

extension DateFormatter {
  static let iso8601Full: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    formatter.locale = Locale(identifier: "en_US_POSIX")
    return formatter
  }()

While your answer didn’t solve my problem it definitely put me on the right track so thank you!

1 Like