-2

I am trying to convert string to date using NSDateFormatter,but some how I am not able to do.

Here is my code:

var dateformatter = NSDateFormatter() // object of NSDataFormatter
dateformatter.dateFormat = "dd-MM-YYYY"  //Format in which I want date
println(dateformatter.dateFromString("2014-12-25 00:00:00"))
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
Diamond King
  • 676
  • 10
  • 17

2 Answers2

1

Three things are wrong with the code; 1) year codes use lower case y's, 2) your date string is reversed, and 3) dateFromString returns an optional. I implicitly unwrapped the date here but you do the right thing as needed.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
println(dateFormatter.dateFromString("25-12-2014")!)

enter image description here

Price Ringo
  • 3,424
  • 1
  • 19
  • 33
0

Try this out :

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-YYYY hh:mm:ss"
let date = dateFormatter.dateFromString("25-12-2014 00:00:00")
println(date)

Edit: You should match 2014-12-25 to dd-MM-YYY like above.

B B
  • 1,950
  • 1
  • 15
  • 15