0

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

这是我正在涉足的代码。

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 年,而我正在检查的日期是今天的日期。我现在是凌晨 3 点,我的大脑一片混乱,所以如果这是有史以来最简单的事情并且我看不到它,请提前道歉。

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

4

1 回答 1

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"];

希望这可以帮助,

哈尔加瓦

要得到:

NSDate *returnedDate = [userDefaults dateForKey:@"storedDate"];
于 2011-12-31T04:20:28.397 回答