2010-12-14 64 views
6

我有一個日曆應用程序,我想從當前日期(NSDate)獲得下一年。從當前NSDate獲取明年?

我該怎麼做?

+1

剛剛從當前日期獲得一年並添加一個。你不知道該怎麼做? – Gabe 2010-12-14 09:04:21

回答

19

您可以NSDateComponents做計算閏年和閏秒的辛勤工作:

NSDate *today = [[NSDate alloc] init]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init]; 
[offsetComponents setYear:1]; 
NSDate *nextYear = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0]; 
5

正如VdesmedT提到的,你可以使用dateByAddingTimeInterval並添加一年的秒數。但更確切地說,你可以做到以下幾點:

NSDate *today = [NSDate date]; // get the current date 
NSCalendar* cal = [NSCalendar currentCalendar]; // get current calender 
NSDateComponents* dateOnlyToday = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:today]; 
[dateOnlyToday setYear:([dateOnlyToday year] + 1)]; 
NSDate *nextYear = [cal dateFromComponents:dateOnlyToday];

希望這會有所幫助。

1

這是我的版本:在swift中。

let calendar = NSCalendar.currentCalendar() 
let newDate = calendar.dateByAddingUnit(.Year, value: 1, toDate: NSDate(), options: NSCalendarOptions.MatchNextTime)