Maysam
Maysam

Reputation: 7367

Swift DateFormatter returns nil while converting String to Date

I'm trying to convert a string:

2018-01-18 13:04:42 +0000

to something like

January, 18, 2018

using DateFormatter but it fails. I have tried other questions (this, this and this).

This is my simple code which prints nil:

let str = "2018-01-18 13:04:42 +0000" 
let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "MMMM, dd, YYYY" 
dateFormatter.locale = Locale.current 
let mydate = dateFormatter.date(from: str) 
print(mydate)

Upvotes: 4

Views: 8286

Answers (2)

glyvox
glyvox

Reputation: 58029

Your DateFormatter expects the original string to be in the January, 18, 2018 format. You should convert it to a Date first and only convert it to another format after that.

Also, you should not use YYYY when referring to an ordinary calendar year. See this question for details.

let str = "2018-01-18 13:04:42 +0000" 
let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" 
dateFormatter.locale = Locale(identifier: "en_US_POSIX") 

guard let date = dateFormatter.date(from: str) else {
    return
}

let newDateFormatter = DateFormatter() 
newDateFormatter.dateFormat = "MMMM, dd, yyyy" 
let newStr = newDateFormatter.string(from: date)
print(newStr) /*January, 18, 2018*/

Upvotes: 7

Tom E
Tom E

Reputation: 1607

A DateFormatter can convert a string into a date only if the format of the date string matches the dateFormat—which isn’t the case in your example. For this reason it correctly responds with a nil reply.

Upvotes: 2

Related Questions