Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

406
Views
How to convert mySQL datetime returned in a JSON object to a Swift date?

I have a JSON object that has a mySQL datetime inside of it that I need to decode in Swift and compare it to another date. How can I convert this mySQL datetime into a Swift date?

Below is what is returned in the JSON object:

{"startDate": "Sun, 02 Aug 2020 00:00:00 GMT"}

This is how we've tried to decode it:

struct jsonDate: Codable {
    let startDate: String
}

let tempDate = try JSONDecoder().decode(jsonDate.self, from: data)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let previousSunday = dateFormatter.date(from: tempDate.startDate)!
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Based on the string you provide for the JSON, the date format you're setting on the formatter is incorrect. The format you set matches ISO-8601-formatted strings, like

2020-02-08 00:00:00 Z

but your string would require a format like

E, dd MMM yyyy HH:mm:ss ZZZZ

instead.

over 4 years ago · Santiago Trujillo Report

0

You can parse your date string using DateFormatter and setting a correct dateFormat:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z"
let previousSunday = dateFormatter.date(from: tempDate.startDate)!

You can take a look at this site NSDateFormatter.com for more information.


Note

I recommend not to force-unwrap optionals:

dateFormatter.date(from: tempDate.startDate)! // crash if `nil`

and provide a default value instead or throw an error:

if let previousSunday = dateFormatter.date(from: tempDate.startDate) {
    // previousSunday is valid
} else {
    // throw an error etc.
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!