views:

64

answers:

2

I have the following code to parse a date from string:

NSString * str = @"8/13/2010 1:59:00 PM";
NSDateFormatter * dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
NSDate * orderDate = [dateFormat2 dateFromString:str ];

but orderDate is always coming up null, what am i doing wrong ? What is the proper dateFormatString ?

This works fine in the emulator but is null on iphone 4 ios 4.0

A: 

The problem isn't the date format, it's that the init method is only supported on Mac OS X v10.4 through Mac OS X v10.5 (which is probably why it works in the simulator). Try using

initWithDateFormat:allowNaturalLanguage:

instead. See here for more information.

highlycaffeinated
@slim Sorry, I was looking at the OS X docs instead of the iOS docs. init is indeed the method to use on iOS.
highlycaffeinated
A: 

using this fix from @Liam 's comment helped me fix this, i'm just posting in case its helpful to someone else,

NSDateFormatter * parser = [[NSDateFormatter alloc] init];
NSLocale * locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]autorelease];
[parser setLocale:locale ];
[parser setFormatterBehavior:NSDateFormatterBehavior10_4];
[parser setDateFormat:@"M/d/yyyy h:mm:ss a"];

NSDate * orderDate = [parser dateFromString:str ];

i realized this bug i found only happens when the iphone user sets their clock to the 24 hour military time,

slim
Changing the format string to `H:mm:ss` should make it compatible with hours from 0-23.
highlycaffeinated
Also, if the date/time value you are getting is dependent on the user's preference settings, you'll probably be better off using the `setDateStyle:` method instead of `setDateFormat:`.
highlycaffeinated
@highlycaffeinated - i don't want to display it as 0-23, also do you have an example on how to use setDateStyle?
slim