iOS - 如何比较两次?
我使用以下函数来检查消息是否已过期 -
- (BOOL) hasExpired:(NSDate*)myDate
{
if(myDate == nil)
{
return false;
}
NSDate *now = [NSDate date];
return !([now compare:myDate] == NSOrderedAscending);
}
如果我比较两个不同的日期,这可以正常工作。但是,如果消息在今天早些时候过期,则返回 false。关于如何修复它有什么想法吗?
I use the following function to check if a message has expired -
- (BOOL) hasExpired:(NSDate*)myDate
{
if(myDate == nil)
{
return false;
}
NSDate *now = [NSDate date];
return !([now compare:myDate] == NSOrderedAscending);
}
This works fine if I am comparing two different dates. However, it returns false if the message has expired earlier in the day today. Any ideas on how I might fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(添加我的评论作为答案:)
这不应该发生,而且
NSDate
实例之间 1 秒的差异就足够了。添加一个包含两个日期的NSLog()
来查看它们是否确实不同。(Adding my comment as an answer:)
This should not happen, also 1 second difference between
NSDate
instances is enough. Add anNSLog()
with both dates there to see whether they are different indeed.您可以使用 NSDate 类的系统方法与当前时间进行比较
返回值是接收者与当前日期和时间之间的间隔。如果接收者早于当前日期和时间,则返回值为负数。
所以正确的代码是
或者如果你想比较 2 个日期,请使用
You can use system method of NSDate class to compare with current time
Return value is the interval between the receiver and the current date and time. If the receiver is earlier than the current date and time, the return value is negative.
So correct code will be
Or if you want to compare 2 dates, use
检查当天是否返回 NSOrderedSame。也许您还需要单独比较时间。
Check to see if it is returning NSOrderedSame when it is the same day. Maybe you need to compare the time as well, separately.