Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

408
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda