我们如何获得下一个日期从输入日期基于给定的重复周期



我是iPhone新手。

我想根据重复周期从给定日期中找出下一个日期。

例如:

我想要的功能如下…

  • 给定日期:2011年5月31日重复:每月作为参数给出,则应返回下一个日期 2011年7月31日(因为6月没有31日)

  • 函数也应该足够智能来计算下一个闰年,如果给定日期:29'Feb 2008重复:每年作为参数给出,那么下一个日期应该返回29'Feb 2012(下一个闰年)

  • 等等重复选项可以是其中之一:每日,每周(在一周的选定日期),每月,每年,无(根本不重复)

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

这是从我如何使用NSDate获得下一个日期复制的?感谢@Massimo Cafaro给出的答案。

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

试试这个:-

- (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;
}

相关内容

  • 没有找到相关文章

最新更新