Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

400
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda