i am using the following function to round the time interval to nearest 5th minute
我使用下面的函数将时间间隔四舍五入到最近的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;
} now i want to rounded the time to nearest tenth minute ..... can any one please help me how to do that thing
现在我想把时间四舍五入到最近的第十分钟……谁能帮我做那件事吗
2 个解决方案
#1
9
Assuming you don't care about seconds:
假设你不在乎秒数:
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)];
#2
0
My take at it, works well with other minutes as well tho i haven't tested.. heh
我对它的理解,和我没有测试过的其他时间一样有效。哈
// 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;
}
#1
9
Assuming you don't care about seconds:
假设你不在乎秒数:
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)];
#2
0
My take at it, works well with other minutes as well tho i haven't tested.. heh
我对它的理解,和我没有测试过的其他时间一样有效。哈
// 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;
}