为什么不能使用< NSDate进行比较?或者>? [英] Why can't NSDate be compared using < or >?

查看:94
本文介绍了为什么不能使用< NSDate进行比较?或者>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"MM/dd/yyyy"];
NSLog([@"today is " stringByAppendingString:[dateFormat stringFromDate:date]]);
NSLog([@"firstBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:firstBirthdayDate]]);
NSLog([@"secondBirthdayDate is " stringByAppendingString:[dateFormat stringFromDate:secondBirthdayDate]]);
if ([firstBirthdayDate isEqualToDate:secondBirthdayDate])
    NSLog(@"First date is the same as second date");
if (firstBirthdayDate < date)
    NSLog(@"First date is earlier than today");
else
    NSLog(@"First date is later than today");

if (secondBirthdayDate < date)
    NSLog(@"Second date is earlier than today");




  • 今天是11/08/2012

  • firstBirthdayDate 是01/23/2012

  • secondBirthdayDate 是01/23/2012

    • Today is 11/08/2012
    • firstBirthdayDate is 01/23/2012
    • secondBirthdayDate is 01/23/2012
    • 以下是我在日志中得到的信息:

      Here's what I get in the log:


      第一个日期与第二个日期相同

      First date is the same as second date

      第一个日期晚于今天

      第二个日期早于今天

      我想我会发疯...

      推荐答案

      使用 if([date1 isEqualToDate:date2])比较两个日期,否则你可以使用以下,

      Use if ([date1 isEqualToDate:date2]) for comparing two dates or else you can use the following,

      if ([date1 compare:date2] == NSOrderedSame)
      
      if ([date1 compare:date2] == NSOrderedAscending)
      
      if ([date1 compare:date2] == NSOrderedDescending)
      

      > < = 仅用于比较非指针。基本上我的理解是,当您使用这些运算符时,它可能是比较内存地址而不是内存中的值。所以你会得到意想不到的结果。

      >, < or = are only for comparing non-pointers. Basically my understanding is that when you are using these operators, it might be comparing the memory addresses rather than the values in it. So you will get unexpected results.

      从逻辑上讲,这是它的工作原理:

      Logically, this is how it works:

          if (obj1 > obj2) {
              return NSOrderedDescending;
          }
      
          if (obj1 < obj2) {
              return NSOrderedAscending;
          }
      
          if (obj1 == obj2) {
              return NSOrderedSame;
          }
      

      您可以使用任何比较语句来比较日期。

      You can use any of the compare statements to compare dates.

      这篇关于为什么不能使用&lt; NSDate进行比较?或者&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆