runmad runmad - 1 month ago 5
Objective-C Question

Convert 24h to 12h time format in Obj-C

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.

Answer

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

NSDateComponents *comps = [[NSDateComponents alloc] init];
[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];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString* dateString = [dateFormatter stringFromDate:date];