苦苦挣扎以存储日期供以后使用

时间:2011-12-29 03:47:46

标签: objective-c ios nsdate nsdateformatter nsdatecomponents

嗨,我对iOS编程非常陌生,正在玩日期(今天的日期和1年后的日期)。

这是我正在涉足的代码。

NSCalendar * calendar = [NSCalendar currentCalendar];//Create a calendar
NSDate *todaysDate = [[NSDate alloc]init]; //get todays date
NSString *dateToday = [NSString stringWithFormat:@"%@",todaysDate];//convert it to a string
NSDateFormatter *df = [[NSDateFormatter alloc] init];// create a formatter
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDate = [df dateFromString: dateToday];// change it back to a proper NSDate

NSDateComponents *components = [[NSDateComponents alloc] init]; // create the components
[components setYear:1];//add 1 year
nextYear = [calendar dateByAddingComponents:components toDate:todaysDate options:0]; // build the year from component into a variable


dateNextYear = [NSString stringWithFormat:@"%@",nextYear];//convert it to a string
NSDateFormatter *yearFormat = [[NSDateFormatter alloc] init];// create a formatter
[yearFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ" ];//input how the date looks as a string
myDateInTheFuture = [yearFormat dateFromString: dateNextYear];// change it back to a proper NSDate


NSLog(@" next years date is %@ ", myDateInTheFuture);
[yearFormat release];
[components release];
[todaysDate release];

我可以从现在起1年后获得当前日期和未来日期,但我不确定如何存储未来的比较日期,我知道我可以使用“比较”项目来检查NSDate,但是当我将每个日期的日期设置为一个变量,它与我正在检查它的今天相比保持相对1年。 凌晨三点我和我的大脑很难如果事先道歉,如果这是最简单的事情,我就是看不到它。

这是我的第一篇文章,所以请放轻松。 感谢

1 个答案:

答案 0 :(得分:1)

我不完全确定你要做什么,但这就是我收集的内容:

您想要获取当前日期,为其添加一年,并操纵生成的日期。

如果不正确,请通知我。

为此,请尝试以下方法:

NSDate *todayDate = [NSDate date]; //Create a date that is set to today
NSDate *resultingDate = [calendar dateByAddingTimeInterval:31556926; //Take the current date and add the amount of seconds in a year to it

如果要永久存储,请使用NSUserDefaults:

设置:

[userDefaults setObject:resultingDate forKey:@"storedDate"];

希望这有帮助,

HBhargava

得到:

NSDate *returnedDate = [userDefaults dateForKey:@"storedDate"];
相关问题