время округления до ближайшей 10-й минуты - PullRequest
3 голосов
/ 09 ноября 2011

Я использую следующую функцию для округления временного интервала до ближайшей 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 ]

9 голосов
/ 09 ноября 2011

Предполагая, что вам нет дела до секунд:

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)];
0 голосов
/ 27 мая 2014

Я так понимаю, хорошо работает и с другими минутами, хотя я не проверял .. хе

// 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...