我是iPhone新手。
我想根据重复期间找出指定日期的下一个日期。
例如:
我想要的功能如下......
给定日期:2011年5月31日和重复:每月作为参数,然后下一个日期应该返回 31'2011年7月(因为六月没有第31天)
如果给定日期:2008年2月29日和重复:每年作为参数,功能应该足够智能,以计算下一个闰年日那么下一个日期应该返回 29'Feb 2012 (下一个闰年)
等等重复选项可以是以下之一:每日,每周(在选定的星期几),每月,每年,无(完全不重复)
答案 0 :(得分:3)
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) yourDate];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
// now build a NSDate object for yourDate using these components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate *thisDate = [gregorian dateFromComponents:components];
[components release];
// now build a NSDate object for the next day
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: yourDate options:0];
[offsetComponents release];
[gregorian release];
这是从How can i get next date using NSDate?复制而来,此信用额转到@Massimo Cafaro以获得此答案。
答案 1 :(得分:0)
要获得明天的日期,请使用dateByAddingTimeInterval方法。
// Start with today
NSDate *today = [NSDate date];
// Add on the number of seconds in a day
NSTimeInterval oneDay = 60 * 60 * 24;
NSDate *tomorrow = [today dateByAddingTimeInterval:oneDay];
将它延长到一周等非常简单
NSTimeInterval oneWeek = oneDay * 7;
NSDate *nextWeek = [today dateByAddingTimeInterval:oneWeek];
答案 2 :(得分:-1)
试试这个: -
- (NSDate *)dateFromDaysOffset:(NSInteger)daysOffset
{
// start by retrieving day, weekday, month and year components for yourDate
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:daysOffset];
NSDate *offsetDate = [gregorian dateByAddingComponents:offsetComponents toDate:self options:0];
[offsetComponents release];
[gregorian release];
return offsetDate;
}