1

I have problem only with some devices NSDateFormatter returning null the date format from the server is "13:05, 10 November 2013".

    NSDate *Now = [NSDate serverDate];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm, d MMM yyyy"];
    NSDate *LastLogin = [dateFormat dateFromString:DateString];

On simulator and few devices works

LastLogin 2013-10-05 00:36:00 +0000 | Now 2013-11-25 14:50:51 +0000

but on some devices

LastLogin (null) | Now 2013-11-25 15:00:22 +0000

Kris Georgiev
  • 140
  • 1
  • 8
  • The devices you have trouble with likely have their 12/24 time setting opposite what the locale defines. This provokes a "feechure" (ie, documented bug) in iOS. To get around this set the locale to something like "en_US_POSIX". See [this thread](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature). – Hot Licks Nov 25 '13 at 15:29

2 Answers2

4

The problem seems to be with locale, just set the locale for the formatter:

NSDate *Now = [NSDate serverDate];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormat setDateFormat:@"HH:mm, d MMM yyyy"];
NSDate *LastLogin = [dateFormat dateFromString:DateString];
Alexey Kozhevnikov
  • 4,249
  • 1
  • 21
  • 29
3

If you're not setting a particular locale, numbers and dates may be parsed differently even with fixed date formats.

The docs have this to say;

If you're working with fixed-format dates, you should first set the locale of the date formatter to something appropriate for your fixed format. In most cases the best locale to choose is en_US_POSIX, a locale that's specifically designed to yield US English results regardless of both user and system preferences.

Extending your code slightly;

NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *Now = [NSDate serverDate];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:enUSPOSIXLocale];
[dateFormat setDateFormat:@"HH:mm, d MMM yyyy"];
NSDate *LastLogin = [dateFormat dateFromString:DateString];
Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294