我正在尝试学习 Objective-C/iPhone SDK,现在我正在做一种播放本地通知的待办应用。
我有一个“timeOfDay”ivar 存储为来自 DatePicker 的 NSDate 和一个“numberOfDays”ivar 存储为一个 NSNumber。
当我按下一个特定的按钮时,我想安排一个本地通知 x numberOfDays 从按下按钮的时间开始,但在特定的 timeOfDay。
我似乎很容易将 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];
关于iphone - 在特定时间 x 天后创建 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8826231/