嗨,我对 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 点,我的大脑一片混乱,所以如果这是有史以来最简单的事情并且我看不到它,请提前道歉。
这是我的第一篇文章,所以请放轻松。谢谢