Arían Taherzadeh
Arían Taherzadeh

Reputation: 35

Date Formatter Parse JSON date

I'm trying to parse a date from a JSON object that is in type string. The format is as follows: "2019-12-04 00:00:00". I am trying to convert it using the following code but, it always returns the default optional value (i.e it fails to convert it), and I have no idea why.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short

let articleDate = dateFormatter.date(from: "\(sectionsNews.News!.created)") ?? Foundation.Date()

print("\(articleDate)"

Upvotes: 0

Views: 192

Answers (1)

vadian
vadian

Reputation: 285072

You are using both style and dateFormat. Don't.

Either specify the style or – in this example – dateFormat. And set the locale to a fixed value.

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"    
let articleDate = dateFormatter.date(from: sectionsNews.News!.created) ?? Date()

Side note:

Creating a string from a string ("\(sectionsNews.News!.created)") is redundant.

Upvotes: 1

Related Questions