I have a calendar application in which I want to get the next year from the current date (NSDate).
How can I do this?
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With