【发布时间】:2011-12-29 03:47:45
【问题描述】:
您好,我是 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 点,我的大脑一片混乱,所以如果这是有史以来最简单的事情,而我只是看不到它,请提前道歉。
这是我的第一篇文章,所以请放轻松。 谢谢
【问题讨论】:
标签: objective-c ios nsdate nsdateformatter nsdatecomponents