Fabio Poloni Fabio Poloni - 2 years ago 118
Objective-C Question

Hours in NSDate everytime in 24-hour style?

Today I have a very simple question but iOS doesn't think so.

I have this date formatter:

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm"];

If I use this:

NSDate *myDate = [timeFormatter dateFromString:@"13:00"];

It returns this:


This is because the simulator has switched off 24-hour. But for my app I really need
instead of

Does anybody know a solution?

Thanks in advance,

--- EDIT 1 ---

Added new code:

NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH:mm"];
NSDate *timeForFirstRow = [timeFormatter dateFromString:@"13:00"];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:timeForFirstRow];
NSInteger hour = [dateComponents hour]; //This will be 1 instead of 13
NSInteger minute = [dateComponents minute];

Answer Source

If you want to force it to 12-hour or 24-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale of the date formatter to en_US_POSIX (for 12-hour), or, say, en_GB for the 24-hour mode.

That is,

NSLocale* formatterLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease];
[timeFormatter setLocale:formatterLocale];

Some more on that here:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download