如何获得与周三匹配的接下来3个月的NSDate列表?

时间:2014-10-30 15:22:41

标签: ios nsdate uilocalnotification nsdatecomponents

我希望使用UILocalNotification为我的应用程序添加提醒功能,但是只有64个已注册的通知限制,并且我的应用程序已计算出用户可能超出该限制。

因此,我现在正在考虑记录用户提醒设置并创建存储在核心数据中的未来通知队列。

每次启动应用程序时,它都会检查通过UILocalNotification注册的通知数量,以及数量是否为<它将从核心数据中分配接下来的24个预定通知,最多可以回到64个。

我目前正在努力研究如何计算从现在到未来3个月之间可能发生的确切日期,我只对所选日期即星期三的日期感兴趣。

提前致谢。

亚伦

1 个答案:

答案 0 :(得分:1)

感谢其他人的反应,我需要阅读文档继承人我最后做了一些帮助。

// Current Date + Time given for initial reminder
NSString *sDateGiven=@"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