objective-c - 时间四舍五入到最接近的第 10 分钟

标签 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;

} 现在我想把时间四舍五入到最近的第十分钟..... 谁能帮我怎么做那件事

最佳答案

假设您不关心秒数:

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/

相关文章:

ios - 实例被释放,而键值观察者仍然在其中注册

ios - 表格 View 中的下拉列表

objective-c - (!object) 和 (object == nil) 之间有区别吗?

objective-c - NSWindowController 应该始终是窗口 Controller 的父类(super class)吗?

ios - 更新时,是否可以对应用程序进行编程以删除其自身的所有内容,然后安装较新的版本?

ios - 在 MKMapView 上更新和组织覆盖

ios - 无法从 UIWebView 获取 HTML 字符串

iphone - 如何对 UIImage 进行去饱和处理?

ios - NSMutableDictionary 键找不到对象

iphone - 将 UIButton 向下移动 10px 并打开新的 ViewController