【问题标题】:How to get a list of NSDates for the next 3 months which match Wednesday?如何获得与周三匹配的未来 3 个月的 NSDates 列表?
【发布时间】:2014-12-26 17:27:28
【问题描述】:

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

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

每次启动应用程序时,它会检查有多少通知注册到 UILocalNotification,如果数量小于 40,它将从核心数据分配接下来的 24 个计划通知,最多备份到 64 个。

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

提前致谢。

亚伦

【问题讨论】:

  • 那么,您是否有任何问题,或者您希望我们查看 NSCalendar 和 NSDateComponents 的文档并告诉您其中的内容?
  • 使用NSCalendar方法dateByAddingComponents:toDate:options:获取下一个NSDate,并重复直到获得所需数量的新日期。

标签: ios nsdate uilocalnotification nsdatecomponents


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多