开发者

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.

[开发者_StackOverflow中文版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.


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];


For someone new like me I struggled with the date formatter and found that the [NSCalendar currentCalendar] will use the users preferences to set timezone. In my situation I wanted to convert a time that a server gave me so it was always wrong. I used this simple function in my case.

- (NSString *)formatTime:(NSString *)time
{
  NSString *hour = [time substringWithRange:NSMakeRange(0, 2)];
  NSString *minute = [time substringWithRange:NSMakeRange(2, 2)];

  NSString *tail = ([hour integerValue] > 11) ? @"PM" : @"AM";    

  return [NSString stringWithFormat:@"%@:%@ %@", hour, minute, tail];    
}


You can try this.It works for me

    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    [df setDateFormat:@"yyyy-mm-dd hh:mm:ss"];

    NSDate* newDate = [df dateFromString:[df stringFromDate:[NSDate date]]];
    [df setDateFormat:@"hh:mm a"];
    newDate = [df stringFromDate:[NSDate date]];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜