开发者

Iphone: How do I 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.

Th开发者_Python百科en add a year to it.

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


You will want to make use of NSCalendar and NSDateComponents in order to perform what you're after. 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 format specified, you can do the following;

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

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜