0

know that there are a lot of similar questions and I need to be more attentive. But I can't understand what's happen in my case.

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"hh:mm:a MM/dd/yyyy"];
NSDate *date = [dateFormatter dateFromString:@"09:21:am 07/22/2014"];

date is nil. need a help. thanks.

Mike
  • 481
  • 10
  • 24
  • 2
    I have just tested and it works for me: date contain 2014-07-22 07:21:00 +0000 – skrew Jul 22 '14 at 02:41
  • Thank you for your help. Will take a look in another place. – Mike Jul 22 '14 at 02:42
  • I think the format should be [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; instead of [dateFormatter setDateFormat:@"hh:mm:a MM/dd/yyyy"]; – Klinkert0728 Jul 22 '14 at 03:17
  • I don't think it can decide the problem. I found it works in iPhone and is happen only in iPad. Seems to me it's because of time zone – Mike Jul 22 '14 at 05:11
  • BTW, it's very non-standard to see the time as `hh:mm:a`. You wouldn't generally use that extra colon. If you need it, go ahead, but it's atypical. – Rob Jul 22 '14 at 05:30
  • Thank you for your note. It wasn't mine. I should to fix it only – Mike Jul 22 '14 at 20:19

1 Answers1

1

To use 12-hour format for parsing, it seems NSDateFormatter needs any 12-hour locale. I don't know this is a kind of bug or not though.

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"es_US"]];
[dateFormatter setDateFormat:@"hh:mm:a MM/dd/yyyy"];
NSDate *date = [dateFormatter dateFromString:@"09:21:am 07/22/2014"];

To find 12-hour format locale, this code helps:

NSArray *locales = [NSLocale availableLocaleIdentifiers];
for(NSString *locale in locales) {
    NSString *fmt = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale localeWithLocaleIdentifier:locale]];
    NSLog(@"%10s:%@", [locale UTF8String], fmt);
}

see this answer

Community
  • 1
  • 1
rintaro
  • 51,423
  • 14
  • 131
  • 139
  • Did you mean `en_US`? That's the common locale used. Or `en_US_POSIX` as described in [Technical Q&A QA1480](https://developer.apple.com/library/ios/qa/qa1480/_index.html). – Rob Jul 22 '14 at 05:26
  • @Rob Thank you for QA, i didn't know that! it seems `en_US_POSIX` is better. I selected `es_US` because it returns `hh a` not 'h a' for `dateFormatFromTemplate:@"j"` result. – rintaro Jul 22 '14 at 05:53