Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hours in NSDate every time in 24-hour style?

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:

 "1:00"

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

--- 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];
like image 227
Fabio Poloni Avatar asked Mar 12 '11 15:03

Fabio Poloni


3 Answers

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:

http://developer.apple.com/iphone/library/qa/qa2010/qa1480.html

like image 139
SVD Avatar answered Sep 23 '22 19:09

SVD


I had this same issue recently and came across this document which lists all the date format patterns: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

I was able to get 24-times working just by using k:mm as the date format:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"k:mm"];
like image 9
Matt Ledger Avatar answered Sep 24 '22 19:09

Matt Ledger


You have to two steps here

NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[formatter setLocale:locale];

[formatter setDateFormat:@"hh:mm a"];

here a in the formatter gives am/pm format

like image 1
Karthik damodara Avatar answered Sep 23 '22 19:09

Karthik damodara