-1

I'm trying to decode a json that has date value inside the json is like this

{
 "id": 2
 "startDate": "2022-08-01T18:44:09.538",
 "endDate": "2023-07-30T03:03:56.249",
 "dateCreated": "2022-07-30T03:05:08.8338403" 
}

and here is my struct model for the Json.

struct JsonResponse: Decodable, Identifiable {
 var id: Int
 var startDate: Date
 var endDate: Date
 var dateCreated: Date
} 

My question is how can I decode these dates and show them in a Text() like "Mon 11/22" format. Thanks for your help.

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    The `iso8601` date decoding strategy doesn't support milliseconds, so you have to add a custom date decoding strategy to decode the string as `Date`. Or to do the bidirectional conversion implement `int(from decoder`. – vadian Aug 16 '22 at 06:00

1 Answers1

0

Yes, you can decode this. If you want to convert String to Date. You can try this:

func getDate(fromDate: String) -> Date {
        
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM d yyyy"
        let date = formatter.date(from: fromDate)!
        
        return date
    } 

And if you want to convert Date into String. You can try this:


func getString(from date: Date) -> String {
        
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM d yyyy"
        let strDate = formatter.string(from: date)
        return strDate
    }

And if you want to convert String to String:


func getStringFrom(strDate: String) -> String {
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let date = formatter.date(from: strDate) ?? Date()

        let outformatter = DateFormatter()
        outformatter.dateFormat = "MMM d yyyy"
        return outformatter.string(from: date)
    }

You can check this for the date formats.

Taimoor Arif
  • 750
  • 3
  • 19