xcode Iphone:如何将年份添加到当前日期并将其作为 2011-11-20 格式的字符串返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3785833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 19:47:03  来源:igfitidea点击:

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

iphonexcodeiphone-sdk-3.0

提问by Jules

I need to get the current date.

我需要获取当前日期。

Then add a year to it.

然后再加一年。

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

并以 YYYY-MM-DD aka 2011-11-20 格式输出结果

回答by John Wordsworth

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.

您将需要使用 NSCalendar 和 NSDateComponents 来执行您想要的操作。像下面这样的东西应该可以解决问题。

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.

希望这可以帮助。