我正在使用以下函数将时间间隔四舍五入到最接近的第 5 分钟

-(NSDate *)roundDateTo5Minutes:(NSDate *)mydate{
// Get the nearest 5 minute block
NSDateComponents *time = [[NSCalendar currentCalendar]
                                              components:NSHourCalendarUnit | NSMinuteCalendarUnit
                                              fromDate:mydate];
NSInteger minutes = [time minute];
int remain = minutes % 5;
// if less then 3 then round down
if (remain<3){
    // Subtract the remainder of time to the date to round it down evenly
    mydate = [mydate addTimeInterval:-60*(remain)];
}else{
    // Add the remainder of time to the date to round it up evenly
    mydate = [mydate addTimeInterval:60*(5-remain)];
}
return mydate;

}
现在我想将时间四舍五入到最接近的十分钟......
任何人都可以帮助我如何做那件事

最佳答案

假设你不关心秒:

NSDateComponents *time = [[NSCalendar currentCalendar]
                              components: NSHourCalendarUnit | NSMinuteCalendarUnit
                                fromDate: mydate];
NSUInteger remainder = ([time minute] % 10);
if (remainder < 5)
    mydate = [mydate addTimeInterval: -60 * remainder];
else
    mydate = [mydate addTimeInterval: 60 * (10 - remainder)];

关于objective-c - 时间四舍五入到最接近的第 10 分钟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8063850/

10-13 05:59