关于 iphone:从现在起 x 天后的特定时间创建 NSDate

Create NSDate at specific time x days from now

我正在尝试学习 Objective-C/iPhone SDK,现在我正在做一种使用本地通知的待办事项应用程序。

我有一个"timeOfDay"ivar 存储为来自 DatePicker 的 NSDate 和一个"numberOfDays"ivar 存储为 NSNumber。

当我按下特定按钮时,我想在按下按钮时但在特定的 timeOfDay 安排本地通知 x numberOfDays。

我似乎很容易将 NSTimeInterval 添加到当前日期,这将使我能够从当前时间安排通知 numberOfDays,但添加 timeOfDay 功能使其变得更加复杂。

实现这一目标的正确方法是什么?

谢谢


使用 NSDateComponents 将时间间隔添加到现有日期,同时尊重用户当前日历的所有怪癖。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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];


有一个非常简单的方法可以做到这一点,它不需要太多的代码行。

1
2
int numDays = 5;
myDate = [myDate dateByAddingTimeInterval:60*60*24*numDays];


1
+ (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date

这应该可以满足您的需求。