我正在尝试学习Objective-C/iPhone SDK,现在我正在做一种使用本地通知播放的待办事项应用程序.
我有一个" timeOfDay "ivar存储为来自DatePicker的NSDate和存储为NSNumber 的" numberOfDays "ivar.
当我按下一个特定的按钮时,我想从按下按钮开始,但是在特定的timeOfDay,安排本地通知x numberOfDays.
我似乎很容易将NSTimeInterval添加到当前日期,这将为我提供一种从当前时间安排通知numberOfDays的方法,但添加timeOfDay功能使其更复杂.
实现这一目标的正确方法是什么?
谢谢
用于NSDateComponents在尊重用户当前日历的所有怪癖的同时将时间间隔添加到现有日期.
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the year, month and day of the current date
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit| NSDayCalendarUnit) fromDate:[NSDate date]];
// Extract the hour, minute and second components from self.timeOfDay
NSDateComponents *timeComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self.timeOfDay];
// Apply the time components to the components of the current day
dateComponents.hour = timeComponents.hour;
dateComponents.minute = timeComponents.minute;
dateComponents.second = timeComponents.second;
// Create a new date with both components merged
NSDate *currentDateWithTimeOfDay = [calendar dateFromComponents:dateComponents];
// Create new components to add to the merged date
NSDateComponents *futureComponents = [[NSDateComponents alloc] init];
futureComponents.day = [self.numberOfDays integerValue];
NSDate *newDate = [calendar dateByAddingComponents:futureComponents toDate:currentDateWithTimeOfDay options:0];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1050 次 |
| 最近记录: |