iOS - 如何比较两次?

发布于 2024-12-22 06:40:06 字数 315 浏览 7 评论 0原文

我使用以下函数来检查消息是否已过期 -

- (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

£噩梦荏苒 2024-12-29 06:40:06

(添加我的评论作为答案:)

这不应该发生,而且 NSDate 实例之间 1 秒的差异就足够了。添加一个包含两个日期的 NSLog() 来查看它们是否确实不同。

(Adding my comment as an answer:)

This should not happen, also 1 second difference between NSDate instances is enough. Add an NSLog() with both dates there to see whether they are different indeed.

舞袖。长 2024-12-29 06:40:06

您可以使用 NSDate 类的系统方法与当前时间进行比较

- (NSTimeInterval)timeIntervalSinceNow

返回值是接收者与当前日期和时间之间的间隔。如果接收者早于当前日期和时间,则返回值为负数。

所以正确的代码是

- (BOOL) hasExpired:(NSDate*)myDate 
{
    return [myDate timeIntervalSinceNow] < 0.f;
}

或者如果你想比较 2 个日期,请使用

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

You can use system method of NSDate class to compare with current time

- (NSTimeInterval)timeIntervalSinceNow

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

- (BOOL) hasExpired:(NSDate*)myDate 
{
    return [myDate timeIntervalSinceNow] < 0.f;
}

Or if you want to compare 2 dates, use

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
裂开嘴轻声笑有多痛 2024-12-29 06:40:06
+(BOOL)isEndDateBigger :(NSDate *)currDate :(NSDate *)endDate {
     if ([currDate compare:endDate] == NSOrderedDescending) {
     NSLog(@"date1 is later than date2");
     return YES; 
     } else if ([currDate compare:endDate] == NSOrderedAscending) {
     return NO;
     } else {
     return NO;
   }
}
+(BOOL)isEndDateBigger :(NSDate *)currDate :(NSDate *)endDate {
     if ([currDate compare:endDate] == NSOrderedDescending) {
     NSLog(@"date1 is later than date2");
     return YES; 
     } else if ([currDate compare:endDate] == NSOrderedAscending) {
     return NO;
     } else {
     return NO;
   }
}
自此以后,行同陌路 2024-12-29 06:40:06

检查当天是否返回 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文