Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dateFromString fails to convert on Iphone set to 24 hour swift

I am trying to use dateFormatter to convert from a string. It works fine on the simulators and works fine on my phone when set to 12 hour time, but fails to set when my phone is set to 24 hour. (It does set when the simulator is set to 24 hour).

passedTime = "10:36 pm"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
let pickerDate = dateFormatter.dateFromString(passedTime)
println(pickerDate)

Like I said, when run on the simulator or on my phone in 12 hour, it works perfect, but when the phone is sett 24 hour, it prints nil. I have read somethings about locale settings, but when I run this on my phone, the local is the same regardless of whether I am in 12 hour or 24 hour mode.

like image 224
David Burnham Avatar asked May 01 '15 03:05

David Burnham


1 Answers

I had exactly the same issue... very frustrating. The solution is to set the locale of your calendar. For Swift 3 it's: yourDateFormatter.locale = Locale(identifier: "en-US")

like image 58
danharsanyi Avatar answered Sep 23 '22 15:09

danharsanyi