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;
}
}
thx a bunch tommy :) – yogi