iphone - 在特定时间 x 天后创建 NSDate

标签 iphone ios cocoa

我正在尝试学习 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/

相关文章:

ios - xCode 不允许添加对象

iphone - 运行项目问题(总是询问登录名和密码)

iphone - 在没有核心位置的情况下查找用户所在城市

iphone - 引脚移动后 MKMapView 刷新

ios - 无法在 Storyboard、Xcode 6.2 中设置类或模块

iOS - 更改 Root View Controller 时获取黑色 View

cocoa - Xcode 重构错误 - "The Selection Does Not Contain Identifiable Content"

objective-c - 如何将 C 风格的 char* 数组转换为 NSArray?

objective-c - 将垃圾收集框架与普通代码混合

iphone - 检索 UIImage 的像素 alpha 值