Ankita Shah
Ankita Shah

Reputation: 2248

dateFromString() returns incorrect date

I'm trying to convert string to Date, but it result incorrect date.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd MMM YYYY"
let dt = dateFormatter.dateFromString("17 Sep 2015")
println("Date : \(dt)") 

It result

Date : Optional(2014-12-20 18:30:00 +0000)

Please let me know where I'm making mistake. I tried other format too, but it return nil.

Upvotes: 2

Views: 1690

Answers (2)

zaph
zaph

Reputation: 112873

The format for year is incorrect, it should be yyyy, not YYYY.

"Y": Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.

See: Date Field SymbolTable.
Also: ICU Formatting Dates and Times

Upvotes: 3

Adam
Adam

Reputation: 26937

Your date format string is wrong. Change it to the following:

dateFormatter.dateFormat = "dd MMM yyyy"

For more information read Date Formatters documentation.

Upvotes: 0

Related Questions