Re: Calculate next occurrence of a NSDate
site_archiver@lists.apple.com Delivered-To: cocoa-dev@lists.apple.com Thanks for the help, Here is what I came up with and from my testing looks to work very well. - (NSInteger)weekDayFromDate:(NSDate *)aDate { NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *components = [gregorianCal components:NSWeekdayCalendarUnit fromDate:aDate]; NSInteger dateWeekDay = [components weekday]; [gregorianCal release]; return dateWeekDay; } - (NSDate *)weeklyNextRun:(NSDate *)startDate { NSDate *today = [NSDate date]; NSInteger startDateWeekDay = [self weekDayFromDate:startDate]; NSInteger todayWeekDay = [self weekDayFromDate:today]; NSInteger daysToAdd; if (startDateWeekDay == todayWeekDay) { daysToAdd = 7; } else if (startDateWeekDay < todayWeekDay ) { daysToAdd = (7 - (todayWeekDay - startDateWeekDay)); } else if (startDateWeekDay > todayWeekDay ) { daysToAdd = (startDateWeekDay - todayWeekDay); } NSDateComponents *components = [[NSDateComponents alloc] init]; [components setDay:daysToAdd]; NSCalendar *gregorianCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *newDate = [gregorianCal dateByAddingComponents:components toDate:today options:0]; [gregorianCal release]; [components release]; return newDate; } Thanks for the help, tom On Dec 31, 2010, at 6:46 AM, WT wrote:
On Dec 31, 2010, at 12:24 PM, Ken Thomases wrote:
On Dec 31, 2010, at 7:22 AM, WT wrote:
The following is straight out of my code, and computes the next Wed or Sat from a given date.
Computing days by calculating the number of seconds in a day will fail when crossing into or out of Daylight Saving Time.
Use -[NSCalendar dateByAddingComponents:toDate:options:] as shown in the documentation.
Regards, Ken
That's an excellent point, Ken, and one which hadn't occurred to me before. Thanks for pointing that out.
WT
_______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/cocoa-dev/site_archiver%40lists.apple... This email sent to site_archiver@lists.apple.com
participants (1)
-
Tom Jones