2009-07-04 78 views

回答

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

嗨, 是的这段代码的工作 非常感谢, 你有什么想法如何获得前一天(昨天)? – Jai 2009-07-04 09:33:27

+0

将[offsetComponents setDay:1]更改为setDay:-1会导致减去一天而不是添加 – rpetrich 2009-07-04 12:42:39

+0

当下一个日期从夏令时移至标准时间时,这也适用。尝试从2011年11月6日移动。感谢@unforgiven。 – johnnieb 2011-08-10 22:43:54

2

//添加以下代码到init方法viewDidLoad中

[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"Date"]; 

//添加该代码,你想获取一个或下一个日期

NSDate *tomorrow = [[NSUserDefaults standardUserDefaults] valueForKey:@"Date"]; 
NSTimeInterval secondsPerDay = 24 * 60 * 60;  
NSDate *date = [tomorrow addTimeInterval:secondsPerDay]; //Change NSDate *date = [tomorrow addTimeInterval:-secondsPerDay]; for yesterday 
tomorrow = date; 
[self setDate:tomorrow]; 
dateTextField.text = [self getDate];   
[[NSUserDefaults standardUserDefaults] setObject:tomorrow forKey:@"Date"]; 
28

这个怎么样的方法呢?

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); 
3

我想这种方法工作得很好,对我来说。

NSString *zajtra = [[NSDate date] dateByAddingTimeInterval:86400]; 
34
NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]]; 

更最简单的方法..

相关问题