Вокруг NSDate к ближайшим 5 минутам

Я всегда проверяю свои дампы структуры базы данных в управлении исходным кодом. Полные дампы базы данных однако я обычно просто сжимаюсь и убираю для устройства хранения данных.

53
задан Forge 5 July 2016 в 21:26
поделиться

4 ответа

Возьмите значение минут, разделите на 5 и округлите в большую сторону, чтобы получить следующую максимальную 5-минутную единицу, умножьте на 5, чтобы вернуть это значение в минутах, и создайте новое значение NSDate.

NSDateComponents *time = [[NSCalendar currentCalendar]
                          components:NSHourCalendarUnit | NSMinuteCalendarUnit
                            fromDate:curDate];
NSInteger minutes = [time minute];
float minuteUnit = ceil((float) minutes / 5.0);
minutes = minuteUnit * 5.0;
[time setMinute: minutes];
curDate = [[NSCalendar currentCalendar] dateFromComponents:time];
54
ответ дан 7 November 2019 в 08:16
поделиться

Я сам искал это, но, используя приведенный выше пример, я получил даты от 0001.

Вот моя альтернатива, объединенная с более элегантным предложением модов smorgan, но будьте осторожны, я не протекаю еще тестировал это:

NSDate *myDate = [NSDate date];
// Get the nearest 5 minute block
NSDateComponents *time = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit
                                                         fromDate:myDate];
NSInteger minutes = [time minute];
int remain = minutes % 5;
// Add the remainder of time to the date to round it up evenly
myDate = [myDate addTimeInterval:60*(5-remain)];
1
ответ дан 7 November 2019 в 08:16
поделиться

Спасибо за образец. Ниже я добавил код, округляющий до ближайших 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;
}
6
ответ дан 7 November 2019 в 08:16
поделиться

Вот мое решение исходной проблемы (округление) с использованием идеи обертки Айянни.

-(NSDate *)roundDateToCeiling5Minutes:(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;
    // Add the remainder of time to the date to round it up evenly
    mydate = [mydate addTimeInterval:60*(5-remain)];
    return mydate;
}
2
ответ дан 7 November 2019 в 08:16
поделиться