Jach0
Jach0

Reputation: 115

Create NSDate at specific time x days from now

I'm trying to learn Objective-C/iPhone SDK and right now I'm doing a kind of to-do app playing with local notifications.

I have a "timeOfDay" ivar stored as an NSDate from a DatePicker and a "numberOfDays" ivar stored as an NSNumber.

When I press a specific button, I would like to schedule a local notification x numberOfDays from the time the button is pressed but at the specific timeOfDay.

I seems easy to add an NSTimeInterval to the current date which would give me the a way to schedule the notification numberOfDays from current time but adding the timeOfDay feature makes it more complex.

What would be the correct way of achieving this?

Thanks

Upvotes: 2

Views: 1067

Answers (3)

Mark Adams
Mark Adams

Reputation: 30846

Use NSDateComponents to add time intervals to an existing date while respecting all the quirks of the user's current calendar.

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];

Upvotes: 8

Bill Burgess
Bill Burgess

Reputation: 14154

There is a pretty simple method to do this that won't involve as many lines of code.

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

Upvotes: 3

Krishna K
Krishna K

Reputation: 708

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

That should give you what you're looking for.

Upvotes: 0

Related Questions