我有以下方法将持续时间(以秒为单位)格式化为格式为@“mm:ss”的字符串。每当输入特定值 60 时,此方法的行为都出乎意料:
- 持续时间 = 59 -> @"00:59"
- 持续时间 = 60 -> @"59:59"(预期为 @"01:00")
- 持续时间 = 61 -> @"01:01"
方法:
+ (NSString *)formatDuration:(NSTimeInterval)duration
{
NSDateFormatter *durationFormatter = [[NSDateFormatter alloc] init];
[durationFormatter setDateFormat:@"mm:ss"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *zeroComponents = [[NSDateComponents alloc] init];
zeroComponents.hour = 0;
zeroComponents.minute = 0;
zeroComponents.second = 0;
NSDate *zeroDate = [calendar dateFromComponents:zeroComponents];
[zeroComponents release];
NSDate *endDate = [NSDate dateWithTimeInterval:duration sinceDate:zeroDate];
return [[durationFormatter autorelease] stringFromDate:endDate];
}