TPeter
TPeter

Reputation: 473

dateFormatter dateFromString error only on iPhone

when running following code

 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "MM/dd/yyyy h:mm:ss a"

 let a:String = "10/24/2015 12:00:00 PM"
 let b:NSDate? = dateFormatter.dateFromString(a)

on simulator b converts as expected to NSDate with correct value on Simulator on iPhone / physical device, b is nil ...

how can I get the correct result also on physical device?? is this an IOS bug or a calendar related issue?

Upvotes: 1

Views: 316

Answers (3)

RyanTCB
RyanTCB

Reputation: 8224

For the benefit of covering the bases for those using a different formatter

I would suggest using dateFormatter.locale = NSLocale(localeIdentifier: "en_US") . This ensures the date on users device is forced to fit your date formatter. Using locale could cause crash if user is using the 24hr format which your formatter doesn't handle.

If your formatter uses HH which is 24hr instead of h which is 12hr use dateFormatter.locale = NSLocale(localeIdentifier: "en_GB")

Upvotes: 1

Abhinav
Abhinav

Reputation: 38162

Set locale on your date formatter:

dateFormatter.locale = NSLocale(localeIdentifier: "en_US")

Upvotes: 0

TPeter
TPeter

Reputation: 473

The following fixed the issue (Thank you RyanTCB):

 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "MM/dd/yyyy h:mm:ss a"
 dateFormatter.locale = NSLocale(localeIdentifier: "en_US")

 let a:String = "10/24/2015 12:00:00 PM"
 let b:NSDate? = dateFormatter.dateFromString(a)

Upvotes: 2

Related Questions