使用 nsdate 比较两个日期
在我的应用程序中,我必须比较两次:当前(即 12:44)和考虑到我尝试过:
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 都会说“不”。请指出我哪里错了。先感谢您。
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];
But any time I launch it, NSLog says "no". Please, suggest where I' m wrong. Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您的
neededDate
将等于“1970/01/01 14:45”
。您需要设置正确的年份和日期。
例如,您可以使用下一种方法获取当前年份、月份:
Because your
neededDate
will be equal to"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:
我认为问题在这里:
应该是:
因为现在对于“14:45”它返回(空)日期
(这是对之前答案的补充:)
I think the problem is here:
should be:
because now for "14:45" it returns (null) date
(this is additionally to previous answer :)
这意味着在您的情况下,needDate 始终高于当前日期。
这可能是因为您以 24 小时格式存储 48 小时字符串。
还将字符串更改为 HH:mm
,验证您存储在 NeededDate 中的值。
这是
本例中的一个小示例,将打印 dec。
it means that in your case, neededDate is always higher than the current date.
this is probably because you store a 48 hour string in a 24 hour format.
change the string to HH:mm
also, verify the value you store in neededDate.
here's a small example
in this case, dec will be printed.