Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter dateFromString and iPhone in 24 Hour Format Confusion

Tags:

I'm having a problem. I get incoming time strings in 12-hour format, and I'm turning them into NSDate objects. When the iPhone is in 12 hour format, no problem. But when it's in 24 Hour format, things go wrong. Here's some sample code to demonstrate:

NSString *theTime = @"3:19 PM"; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"h:mm a"]; // "3:19 PM" NSDate *date = [formatter dateFromString:theTime]; NSString *theString = [formatter stringFromDate:date]; 

In 24 hour mode, date is 1970-01-01 03:19:00, and theString is "3:19" - WRONG

In 12 hour mode, date is 1970-01-01 15:19:00, and theString is "3:19 PM" - RIGHT

So... question 1: why is the device's 24 hour setting overriding my date formatter setting?

and more importantly, question 2: How do I get a proper conversion from 12 hour time to 24 hour time?

I already have code to detect if the phone is in 24 hour mode, but other than digging around in the string and swapping the 3 with a 15, there doesn't seem to be a clean way to do this.

like image 249
Silromen Avatar asked Feb 01 '10 00:02

Silromen


1 Answers

Not sure if you still need it, but I've had a similar problem which got solved by setting the locale for the date formatter. That is, if you want to force it to 12-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale to en_US_POSIX.

like image 183
SVD Avatar answered Sep 29 '22 02:09

SVD