将时间转换为 HH:MM

Converting time to HH:MM

我目前有一个浮点值,例如 12.5、4、17.5。我希望这些对应于时间 12:30PM、4:00AM 和 5:30PM。

我目前已经通过 hack

取得了接近于此的成绩
if (time > 12.5) {
        time = abs(roundedValue - 12);
        [lab setText:[NSString stringWithFormat:@"%i:00PM",(int)time]];
    } else {
        [lab setText:[NSString stringWithFormat:@"%i:00AM",(int)time]];
    }

但我知道这是不好的做法。将这些数字转换为时间的更好方法是什么?

您可以使用以下-

NSNumber *time = [NSNumber numberWithDouble:([yourTime doubleValue] - 3600)];
NSTimeInterval interval = [time doubleValue];
NSDate *yourDate = [NSDate date];
yourDate = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HH:mm:ss"];

NSLog(@"result: %@", [dateFormatter stringFromDate:yourDate]);

通过执行以下操作解决:

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:0];

NSDate *today10am = [calendar dateFromComponents:components];
NSDate *newDate = [NSDate dateWithTimeInterval:roundedValue*60*60 sinceDate:today10am];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm aa"];
[lab setText:[dateFormat stringFromDate:newDate]];

对不起热舔,我想这在我的理解范围之内。

这只是基础数学,你有一个值,比如 12.5,它由小时数 12 和小时的小数部分 0.5 组成。一个小时有 60 分钟,所以分钟数就是 60 的分数。

如果您想使用 12 小时制,则有一个小问题,大于 12 的小时数需要减去 12,但中午 (12) 是下午,午夜(0 或 24)是上午。因此 am/pm 的测试与是否减去 12.

的测试不同

这是一种方法(只需最少的检查):

NSString *hoursToString(double floatHours)
{
   int hours = trunc(floatHours); // number of hours
   int mins = round( (floatHours - hours) * 60 ); // mins is the fractional part times 60
   // rounding might result in 60 mins...
   if (mins == 60)
   {
      mins = 0;
      hours++;
   }
   // we haven't done a range check on floatHours, also the above can add 1, so reduce to 0 -> 23
   hours %= 24;

   // if you are using 24 hour clock you can finish here and format to the two values

   BOOL pm = hours >= 12; // 0 - 11 = am, 12 - 23 = pm
   if (hours > 12) hours -= 12; // 13 - 23 -> 1 -> 11

   return [NSString stringWithFormat:@"%d:%02d %s", hours, mins, (pm ? "pm" : "am")];
}

您可以简单地称其为:

hoursToString(13.1) // returns 1:06 pm

无需使用NSDate .

HTH