28

I have the following code.

NSDateFormatter *df = ...;
[df setTimeZone:[NSTimeZone defaultTimeZone]];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
NSDate * date = [df dateFromString:date_string]; //here is the problem

In 24-hour mode everything is ok. When 12-hour mode is set on device, stringFromDate returns null. Format of date_string is the same all the time, date format too. Why does it happen?

aleroot
  • 68,849
  • 28
  • 172
  • 209
Sergey
  • 1,118
  • 2
  • 12
  • 27

4 Answers4

55

In your NSDateFormatter "yyyy-MM-dd'T'HH:mm:ss.SSSZZZ" HH stands for 24 hour and hh stands for 12 hour

Omar Abdelhafith
  • 21,143
  • 5
  • 51
  • 55
37

Try to set the locale in this way :

NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
df.locale = twelveHourLocale;

To force instead to 24 hour, you can use :

NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
aleroot
  • 68,849
  • 28
  • 172
  • 209
6

12-hour mode to 24 hour mode:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSDate *amPmDate = [formatter dateFromString:amPmHourString];
[formatter setDateFormat:@"HH:mm"];
NSString *24HourString = [formatter stringFromDate:amPmDate]];

For 24-hour mode to 12 hour mode just do the opposite

Luis Ascorbe
  • 1,865
  • 1
  • 19
  • 35
4
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc] 
                initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
[dateFormat setLocale:locale];
Sagar Desai
  • 337
  • 1
  • 3
  • 11