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

398
Views
¿Cómo convertir mySQL datetime devuelto en un objeto JSON a una fecha Swift?

Tengo un objeto JSON que tiene una fecha y hora mySQL dentro que necesito decodificar en Swift y compararlo con otra fecha. ¿Cómo puedo convertir esta fecha y hora mySQL en una fecha Swift?

A continuación se muestra lo que se devuelve en el objeto JSON:

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

Así es como hemos intentado decodificarlo:

 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

Según la cadena que proporciona para el JSON, el formato de fecha que está configurando en el formateador es incorrecto. El formato que establezca coincide con las cadenas con formato ISO-8601, como

 2020-02-08 00:00:00 Z

pero su cadena requeriría un formato como

 E, dd MMM yyyy HH:mm:ss ZZZZ

en cambio.

over 4 years ago · Santiago Trujillo Report

0

Puede analizar su cadena de fecha usando DateFormatter y configurando un dateFormat de fecha correcto:

 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)!

Puede echar un vistazo a este sitio NSDateFormatter.com para obtener más información.


Nota

Recomiendo no forzar el desenvolvimiento de opcionales:

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

y proporcione un valor predeterminado en su lugar o arroje un 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!