获取正确的日期并设置通知ios

时间:2015-07-09 11:38:59

标签: ios nsdate nscalendar nsdatecomponents

我正在尝试为每个星期六和星期日设置重复通知,但由于某种原因,日期出错了。这是我的代码

NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekOfMonth |NSCalendarUnitWeekOfMonth;
NSDateComponents *comps = [calendar components:unitFlags fromDate:[NSDate date]];
NSDateComponents *dt = [[NSDateComponents alloc]init];
comps.hour   = hour;
comps.minute = [[goal.reminderTimeInfo valueForKey:@"minutes"] intValue];
[dt setMonth:[comps month]];
[dt setYear:[comps year]];
[dt setWeekOfMonth:[comps weekOfMonth]];
comps.weekday = 1;  //Sunday
[dt setWeekday:[comps weekday]];

NSDate *sundayDate = [calendar dateFromComponents:dt];

它假设发出

2015-07-05 19:00:00 +0000

但它的给予

2015-07-04 19:00:00 +0000

如果给当地通知一个特定的日期。例如它的星期日。它会在每个星期天开火吗?

1 个答案:

答案 0 :(得分:1)

您没有更改dt的小时和分钟,但是没有更改comps。

NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitWeekday | NSCalendarUnitWeekOfYear | NSCalendarUnitWeekOfMonth |NSCalendarUnitWeekOfMonth;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:[NSDate date]];
    NSDateComponents *dt = [[NSDateComponents alloc]init];

    dt.hour   = 19;
    dt.minute = 00;
    [dt setMonth:[comps month]];
    [dt setYear:[comps year]];
    [dt setWeekOfMonth:[comps weekOfMonth]];
    [dt setWeekday:1];

    NSDate *sundayDate = [calendar dateFromComponents:dt];