如何使用NSDate获取下一个日期?

Jai*_*Jai 23 iphone nsdate ios

可能重复:
iOS并找到明天

如何使用NSDate获取下一个日期.请把解决方案发给我

Mas*_*aro 57

在下面,yourDate表示您的输入NSDate; nextDate代表第二天.

// start by retrieving day, weekday, month and year components for yourDate
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate: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:thisDate options:0];
    [offsetComponents release];
    [gregorian release];
Run Code Online (Sandbox Code Playgroud)

  • 此代码应该崩溃,因为您要释放两次组件. (2认同)

Par*_*hod 35

NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]];
Run Code Online (Sandbox Code Playgroud)

更简单的方式..

  • 当日期范围内的夏令时更改时,这可能会给出错误的结果. (23认同)
  • 还有闰秒的时候. (6认同)

S.P*_*.P. 31

这个方法怎么样?

http://www.drobnik.com/touch/2009/05/adding-days-to-nsdate/

NSDate *now = [NSDate date];
int daysToAdd = 50;  // or 60 :-)

// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(@"Clean: %@", newDate2);
Run Code Online (Sandbox Code Playgroud)

  • **比本主题中最受欢迎的解决方案更好** (2认同)