Iphone: how to add a year to the current date and return it as a string in the format 2011-11-20

I need to get the current date.

Then add a year to it.

And print the result in the format YYYY-MM-DD aka 2011-11-20

+3
source share
1 answer

You want to use NSCalendar and NSDateComponents to accomplish what you need. Something like the following should do the trick.

NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:1];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:todaysDate  options:0];
[dateComponents release];
[gregorian release];

To then output the target date as a string in the specified format, you can do the following:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
NSString* dateString = [dateFormatter stringFromDate:targetDate];

Hope this helps.

+13
source

Source: https://habr.com/ru/post/1766354/


All Articles