Swift Date Formatter - Different Date from String

Viewed 281

I have the following string and I want to convert it to Date:

"November 8, 2018 12:30 PM"

What I am doing is the next:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy h:mm a"
let date = dateFormatter.date(from: "November 8, 2018 12:30 PM")

But I am getting

2018-11-08 18:30:00 +0000

and I don't know why. Any tip for this?

2 Answers

The date formatter implicitly uses your current timezone, meaning it interprets that date as a local time, then coverts it to a date object with no timezone (UTC+0). It looks like your local time is UTC-6? If I run your code I get 2018-11-8 17:30:00 +0000 because I live in UTC-5

If you use the same formatter to convert the date back to a string, you'll get the same string you put in

dateFormatter.string(from: date)

So no information is being lost. If your string needs to be interpreted in a different timezone other than the current one, you need to set the formatter's timeZone property before parsing it.

There are tools out there I like to use https://nsdateformatter.com/

The format you are explicitly looking for is "MMMM d, yyyy h:m a"

Your code should read something like:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM d, yyyy h:m a"
let date = dateFormatter.date(from: "November 8, 2018 12:30 PM")
let dateString = dateFormatter.string(from: date!)

Related