0

我試圖獲得的NSMutableArray每個NSDate對象的目標爲從現在開始的接下來的24小時內最接近的舍入HH:00或HH:30。24小時除以30分鐘 - NSDate

可以說,現在的02:31我要的@輸出[03:00,03:30,04:00,04:30 ... 03:00(次日)

如果它02:29那麼我想@ [02:30,03:00等到第二天02:30]。

現在我有下面的代碼,幾乎所有的時候都能正常工作,但很少有我想要的所有NSDate對象的輸出,剩下的多餘的時間(@ [03:01,03:31 :04:01 ...等等])。

有什麼想法?

-(NSMutableArray*)TwentyFourHoursFromNowDivicedBy30Mins 
{ 

    NSMutableArray * dateArray = [NSMutableArray array]; 
    NSCalendar * cal = [NSCalendar currentCalendar]; 

    NSDateComponents * plusDays = [NSDateComponents new]; 
    NSDate * now = [self changeTimeValue:[NSDate date]]; 

    for(NSUInteger day = 0; day < 2; day++) 
    { 
     [plusDays setDay:day]; 
     [dateArray addObject:[cal dateByAddingComponents:plusDays toDate:now options:0]]; 
    } 

    NSDate *startDate = [dateArray objectAtIndex:0]; 
    NSDate *endDate = [dateArray objectAtIndex:1]; 
    NSDateComponents *diff = [[NSDateComponents alloc] init]; 
    [diff setMinute:0]; 
    NSCalendar *calz = [NSCalendar currentCalendar]; 
    NSDate *tmp = startDate; 

    NSMutableArray *dates = [NSMutableArray arrayWithObject:tmp]; 

    while ([tmp laterDate:endDate] == endDate) { 
     [diff setMinute:[diff minute] + 30]; 
     tmp = [calz dateByAddingComponents:diff toDate:startDate options:0]; 
     [dates addObject:tmp]; 

    } 


    return dates; 

} 
- (NSDate *)changeTimeValue:(NSDate *)dateValue{ 
    NSDateComponents *time = [[NSCalendar currentCalendar] 
           components:NSHourCalendarUnit | NSMinuteCalendarUnit 
           fromDate:dateValue]; 
    long val = 0; 
    NSDate *newDate = [[NSDate alloc] init]; 
    NSInteger minutes = [time minute]; 
    if(minutes > 0 && minutes < 30) { 
     val = 30 - minutes; NSTimeInterval aTimeInterval = [dateValue 
                  timeIntervalSinceReferenceDate] + 60 * val + minutes; 
     newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval]; 
     return newDate; 
    } else if(minutes > 30 && minutes < 60) { 
     val = 60 - minutes; 
     NSTimeInterval aTimeInterval = [dateValue timeIntervalSinceReferenceDate] 
     + 60 * val; 
     newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval]; 
     return newDate; 
    } else { 
     return newDate; 
    } 
} 

回答

0

你不是在你的changeTimeValue歸零秒,並且在任何情況下,我想你已經過於複雜了。所以我懷疑你後來看到了四捨五入的問題。只需使用NSDateComponents即可完成整個工作:

NSCalendar *currentCalendar = [NSCalendar currentCalendar]; 

NSDateComponents *dateComponents = [currentCalendar 
           components:NSHourCalendarUnit | 
             NSMinuteCalendarUnit | 
             NSYearCalendarUnit | 
             NSMonthCalendarUnit | 
             NSDayCalendarUnit 
           fromDate:dateValue]; 

dateComponents.minute += 15; 
dateComponents.minute -= dateComponents.minute%30; 

return [currentCalendar dateFromComponents:dateComponents]; 
+0

thx a bunch tommy :) – yogi