2011-11-09 138 views
3

我使用下面的函數圓的時間間隔最近的5分鐘時間四捨五入到最接近的第10分鐘

-(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; 

} 現在我想四捨五入的時間最接近的第十分鐘..... 任何一個可以請幫我該怎麼做的事情

回答

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

謝謝。由於您發佈了(〜iOS4.0)addTimeInterval:已被折舊並被替換爲dateByAddingTimeInterval: – Dermot

0

我拿吧,與行吟詩人效果很好r分鐘以及壽我沒有測試..嘿

// 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; 
} 
相關問題