本文介绍了使用nsdate比较两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我必须比较两次:当前(这是12:44)并且考虑到我尝试过:

In my app I have to compare two times: current (which is 12:44) and given I tried:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm"];
NSDate *neededDate = [[NSDate alloc] init];
neededDate = [dateFormatter dateFromString:@"14:45"];
if ([neededDate compare:[NSDate date]] == NSOrderedAscending) {
NSLog(@"yes");
} else NSLog(@"no");
[neededDate release];
[dateFormatter release];

但是当我启动它时,NSLog会说不。请,建议我错了。先谢谢你。

But any time I launch it, NSLog says "no". Please, suggest where I' m wrong. Thank you in advance.

推荐答案

因为 neededDate 将等于1970/01/01 14:45

您需要设置正确的年份和日期。

You need to set correct year and date.

您可以获得当前年,月,并说,例如,使用下一种方法:

You can get current year, month and say, for example, using next approach:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
NSLog(@"Current year: %d", components.year);
NSLog(@"Current month: %d", components.month);
NSLog(@"Current day: %d", components.day);

这篇关于使用nsdate比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 15:29