views:

30

answers:

2

I currently display time in 24h format, because it's the easiest thing for me to do right now with the data I have.

I get the time in "minutes since midnight", so for example, 07:00 or 7:00 a.m is "420" and 21:30 or 9:30 p.m is "1290" and so on.

[NSString stringWithFormat:@"%02d:%02d - %02d:%02d", (open / 60), (open % 60), (close / 60), (close % 60)]

Is there a nice way to use NSDateFormatter to convert from 24h to 12h? I have tried a bunch of things, but I never end up with 100% correct formatting.

I have also tried with lots of if statements, only to end up with way too many lines of code, which should be completely unnecessary in my opinion for such a relatively "easy" job.

Also, no matter I try I also end up with wrong 12h formatting for hours without "1" in the beginning, for example "09:30 a.m.", etc. I can strip this by looking for the suffix, but again this just seems to tedious and weird.

A: 

check if your minutes are less than 720 (12 hours), if so its AM, if not its PM (so you would do hours -12 to get from military to 12h) then add the suffix as needed. Its not pretty, but its a relatively simple formatting job.

Jesse Naugher
Yeah, that's what I did for the "if statement solution" and like said; not pretty :)
Canada Dev
date formatting generally isnt..and thats not a lot of ifs..its one, maybe two.
Jesse Naugher
A: 

Your should really use the system's default date formatting:


NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setHour:hours];
[comps setMinute:minutes];
NSDate* date = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSString* dateString = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterLongStyle];

Or if you insist you can do


NSDateFormatter dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString* dateString = [dateFormatter stringFromDate:date];
Aleph
Thanks! I have merged the two above and if the time has a "0" prefix, I just remove it.
Canada Dev
Or you can set the format to `@"h:mm a"` (one 'h')
Aleph