0

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)"
koen
  • 5,383
  • 7
  • 50
  • 89
  • See vadian’s answer. But the other question is that if you’re writing date strings in some fixed format, like `"yyyy-MM-dd HH:mm:ss"`, you have to ask whether your intent was really to write these in your local timezone, or whether you wanted to store them in GMT/UTC/Zulu format, so that if you ever share that with a server, there’s no ambiguity about time zones. Almost always, for JSON date formatters, you want to send/receive dates in GMT, e.g., `dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)`. Formatter for UI should not specify timezone, but formatter for JSON generally does. – Rob Dec 19 '19 at 17:07

1 Answers1

1

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    The locale should be assigned first, before assigning the date format. Compare https://stackoverflow.com/a/40702569/1187415. – Martin R Dec 19 '19 at 16:24
  • @MartinR Thanks, I didn't realize that the order matters. – vadian Dec 19 '19 at 16:26
  • @vadian are there other locale identifiers that I can use so that it displays relative to the current time (i.e 1 min ago, 4 hours, 1 week ago) or is this a completely different operation? – Arían Taherzadeh Dec 19 '19 at 16:47
  • That's a completely different operation. – vadian Dec 19 '19 at 16:52
  • Often we use [`DateComponentsFormatter`](https://developer.apple.com/documentation/foundation/datecomponentsformatter) for showing nicely formatted string for time elapsed between two dates. – Rob Dec 19 '19 at 16:59