时间四舍五入到最近的第10分钟

时间:2011-11-09 10:46:44

标签: objective-c

我正在使用以下功能将时间间隔四舍五入到最近的第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;

} 现在我想把时间缩短到最近的第十分钟..... 任何人都可以帮我怎么做那件事

2 个答案:

答案 0 :(得分:9)

假设你不关心秒:

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

答案 1 :(得分:0)

我对它的看法,与其他分钟一起运作也很好,我没有经过测试......嘿

// Rounds down a date to the nearest 10 minutes
+(NSDate*) roundDateDownToNearest10Minutes:(NSDate*)date {
    NSDateComponents *time = [[NSCalendar currentCalendar]
                              components: NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit
                              fromDate: date];
    int unroundedMinutes = [time minute];
    int roundedMinutes = (unroundedMinutes / 10) * 10;

    [time setMinute:roundedMinutes];
    NSDate* roundedDate = [[NSCalendar currentCalendar]  dateFromComponents:time];

    return roundedDate;
}