1
- (NSDate*) parseTime:(NSString*) time
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"MMMM dd, yyyy hh:mm a"];

    NSDate* date = [dateFormatter dateFromString:time];

    return date;
}

Where time = "08 12, 2014 08:00 PM " and it is returning nil.

I'm new to this and have tried searching around on everything including Apples help docs, but could use a little more help here to finish pointing me in the right direction please.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Does your string really have a space after "PM"? That would cause the problem. – rmaddy Aug 12 '14 at 20:33
  • 3
    Use `MM`, not `MMMM`. The former will match a two digit number, the latter will match the month name spelled out. – Rob Aug 12 '14 at 20:43
  • 2
    Bookmark this. http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns – CrimsonChris Aug 12 '14 at 20:45
  • Whenever dateFromString returns nil you should always *carefully* validate your format string against the standard (as linked by @CrimsonChris). This is the cause of your trouble about 98% of the time. – Hot Licks Aug 12 '14 at 20:56
  • Thanks guys, those adjustments worked. I added in control to make sure there is no trailing or leading whitespace and everything is now working. I really appreciate the help. – Mike Wohlrab Aug 12 '14 at 20:59
  • You also need to be aware of the [locale "feature"](http://stackoverflow.com/q/6613110/581994). – Hot Licks Aug 12 '14 at 20:59

1 Answers1

1

Try adjusting like the following:

[dateFormatter setDateFormat:@"MM dd, yyyy hh:mm a"];

And dont forget to set the timezone on your formatter to avoid unexecpted result, for example:

dateFormatter.timeZone  = [NSTimeZone timeZoneWithAbbreviation:@"EDT"];

Very Important link by posted by @CrimsonChris:

LOCALE DATA MARKUP LANGUAGE (LDML)

meda
  • 45,103
  • 14
  • 92
  • 122
  • @HotLicks what specs ?? – meda Aug 12 '14 at 21:00
  • Thank you. Everything is all working now. I added in control to remove trailing and leading whitespaces. The time zone is is defaulted to CST but we control adding in time zone adjustment later on in the code. Thank you for that info as I'm sure it will come in handy later. – Mike Wohlrab Aug 12 '14 at 21:02
  • See the link above by @CrimsonChris. Anyone who works much with Objective-C should have it bookmarked. – Hot Licks Aug 12 '14 at 21:03