多虧了別人,我需要閱讀繼承人我結束了與一些幫助做文檔的任意球。
// Current Date + Time given for initial reminder
NSString *[email protected]"28-10-2014 2:15:00 PM";
int dayOfWeekToRemind = 4; // Wednesday
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
[formatter setDateFormat:@"dd-MM-yyyy h:mm:ss a"];
// Convert to NSDate
NSDate *alarmDate = [formatter dateFromString:sDateGiven];
NSCalendar *calendar = [NSCalendar currentCalendar];
// Now we need to work out Next Wednesday
NSDateComponents *componentsForFireDate1 = [calendar components:(NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit| NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfYearCalendarUnit) fromDate: alarmDate];
[componentsForFireDate1 setWeekday: dayOfWeekToRemind] ; // Set to Wednesday
// Check if the date given is before or after wednesday as we are only interested in future Wednesdays
if ([componentsForFireDate1 weekday] > dayOfWeekToRemind) {
// If greater we add a week
[componentsForFireDate1 setWeekOfYear: [componentsForFireDate1 weekOfYear] + 1];
}
// Now we have the very first start date for the next Wednesday
alarmDate = [calendar dateFromComponents:componentsForFireDate1];
int i = 0;
// Loop through 30 weeks
for (i = 0; i < 30; i++) {
NSDateComponents *componentsForFireDate = [[NSDateComponents alloc] init];
[componentsForFireDate setWeekday: 7] ; // Add 7 days
alarmDate = [calendar dateByAddingComponents:componentsForFireDate toDate:alarmDate options:0];
NSLog(@"Date = %@", alarmDate);
}
然後再輸出如下:
Given Date Date 2014-10-28 14:15:00 +0000
ADJUST DATED 2014-10-29 14:15:00 +0000
Date = 2014-11-05 14:15:00 +0000
Date = 2014-11-12 14:15:00 +0000
Date = 2014-11-19 14:15:00 +0000
Date = 2014-11-26 14:15:00 +0000
Date = 2014-12-03 14:15:00 +0000
Date = 2014-12-10 14:15:00 +0000
Date = 2014-12-17 14:15:00 +0000
Date = 2014-12-24 14:15:00 +0000
Date = 2014-12-31 14:15:00 +0000
那麼,你有一個問題,或者你要我們來看看爲NSCalendar和NSDateComponents的文件,並告訴你它說什麼? – 2014-10-30 15:25:03
使用'NSCalendar'方法'dateByAddingComponents:toDate:options:'獲取下一個'NSDate',並重復,直到你有所需數量的新日期。 – Rob 2014-10-30 15:43:09