0

I trying to convert a NSString that looks like this:

@"00:00 15 September 2012"

to a NSDate.

I can't figure out what the unicode format needs to be. I am trying this:

@"HH:mm dd MMMM YYYY"
@"HH:mmddMMMMYYYY"

I've been trying to follow the rules here but to no avail.


EDIT:

Paul's answer does work (except for military time problem). I was trying to use Apple's example of how to create a format template like so:

NSString *formatString = [NSDateFormatter dateFormatFromTemplate:@"hh:mm dd MMM yyyy" options:0
                                                              locale:[NSLocale currentLocale]];

NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:formatString];

This causes everything to spit out null.

However, if I do this:

NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:@"hh:mm dd MMM yyyy"];

All is well in the world. My only guess is that NSLocale doesn't work in simulator?

random
  • 8,568
  • 12
  • 50
  • 85

1 Answers1

1

You wasn't far off, you need something like:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH:mm dd MMM yyyy";
dateFormatter.timeZone = [[NSTimeZone alloc] initWithName:@"GMT"];

NSLog(@"%@", [dateFormatter dateFromString:@"00:00 15 September 2012"]);
Paul.s
  • 38,494
  • 5
  • 70
  • 88
  • Thank you for your help! That does work but is `00:00` correct for handling military time? Anytime that is `12:59+` spits out `null`. – random Sep 14 '12 at 23:23
  • Ah, go it. I updated my question if you could take a look at it again. – random Sep 14 '12 at 23:27
  • Yeah, "hh" is a 12-hour clock, while "HH" is a 24-hour clock. [Except when the user sets the 12/24 switch in Settings "backwards"](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformater-locale-feature). – Hot Licks Sep 15 '12 at 02:27