Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get next year from the current NSDate?

I have a calendar application in which I want to get the next year from the current date (NSDate).

How can I do this?

like image 937
ManthanDalal Avatar asked Dec 14 '10 08:12

ManthanDalal


2 Answers

You can make NSDateComponents do all the hard work of calculating leap years and leap seconds:

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];
like image 193
Claus Broch Avatar answered Sep 21 '22 13:09

Claus Broch


As VdesmedT mentioned, you can use dateByAddingTimeInterval and add the seconds of one year. But to be more precise, you can do the following:

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

Hope this helps.

like image 20
crosscode Avatar answered Sep 20 '22 13:09

crosscode