【问题标题】:iOS: Compare two datesiOS:比较两个日期
【发布时间】:2011-09-01 00:13:10
【问题描述】:

我有一个NSDate,我必须将其与其他两个NSDate 进行比较,我尝试使用NSOrderAscendingNSOrderDescending,但如果我的日期在其他两个日期相同?

示例:如果我有一个 myDate = 24/05/2011 和另外两个是一个 = 24/05/2011 和两个 24/05/2011 我可以使用什么?

【问题讨论】:

  • 我不完全理解你的问题,你想达到什么目的?
  • 日期一和日期二可以是一 = 15/05/2011 和二 = 31/05/2011 但它们也必须是同一天 一 = 24/05/2011 和二 = 24/ 05/2011 然后我必须检查 myData 是否介于日期一和日期二之间
  • 只需提取年、月、日并按顺序进行比较。如果有平局,则比较下一个字段。

标签: objective-c ios nsdate


【解决方案1】:

根据Apple documentation of NSDate compare:

返回一个 NSComparisonResult 值,该值指示接收者的时间顺序和另一个给定日期。

- (NSComparisonResult)compare:(NSDate *)anotherDate

参数 anotherDate

用来比较的日期 接收者。该值不能为零。 如果值为 nil,则行为为 未定义,未来可能会改变 Mac OS X 版本。

返回值

如果:

receiver 和 anotherDate 是 完全相等, NSOrderedSame

接收方稍后 时间比另一个日期, NSOrderedDescending

接收者是 时间早于另一个日期, NSOrderedAscending

换句话说:

if ([date1 compare:date2] == NSOrderedSame) ...

请注意,在您的特定情况下,阅读和编​​写此内容可能更容易:

if ([date2 isEqualToDate:date2]) ...

Apple Documentation about this one

【讨论】:

  • 但是 f ([date1 compare:date2]==NSOrderedSame) 还要检查小时分钟和秒,我不想要它
  • 你的问题有点不清楚抱歉,看看stackoverflow.com/questions/1889164/3092009#3092009,你会找到答案的。
  • 这个答案在两个方面都是正确的。要控制要比较的日期组件,请使用 NSDateComponents
【解决方案2】:

经过搜索,我得出的结论是最好的方法是这样的:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

您也可以将其更改为小时之间的差异。


如果您只想比较日期格式为 dd/MM/yyyy,则需要在 NSDate* currentdate = [NSDate date]; && NSTimeInterval distance 之间添加以下行

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];

【讨论】:

  • 谢谢,这比 compare 或 isEqualToDate 效果更好
  • 同意。我在使用 compare & isEqualToDate 时发现了问题。当然,它可能是额外的 2 行代码,但它更可靠。
【解决方案3】:

我认为您是在问比较函数中的返回值是什么。

如果日期相等则返回NSOrderedSame

如果升序(第二个参数>第一个参数)返回NSOrderedAscending

如果降序(第二个参数NSOrderedDescending

【讨论】:

  • 考虑升序和降序的好方法。
【解决方案4】:

我不知道你是否问过这个问题,但如果你只想比较 NSDate 的日期组件,你必须使用 NSCalendar 和 NSDateComponents 来删除时间组件。

这样的东西应该作为 NSDate 的一个类别:

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}

【讨论】:

    【解决方案5】:

    NSDate 实际上表示自参考日期以来的时间间隔(以秒为单位)(我认为是 2000 年 1 月 1 日 UTC)。在内部,使用双精度浮点数,因此即使两个任意日期在同一天,它们也极不可能比较相等。如果您想查看特定日期是否在特定日期,您可能需要使用NSDateComponents。例如

    NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setYear: 2011];
    [dateComponents setMonth: 5];
    [dateComponents setDay: 24];
    /*
     *  Construct two dates that bracket the day you are checking.  
     *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
     */
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
    NSDateComponents* oneDay = [[NSDateComponents alloc] init];
    [oneDay setDay: 1];
    NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
    /*
     *  Compare the date with the start of the day and the end of the day.
     */
    NSComparisonResult startCompare = [startOfDate compare: myDate];
    NSComparisonResult endCompare = [endOfDate compare: myDate];
    
    if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
    {
        // we are on the right date
    } 
    

    【讨论】:

      【解决方案6】:

      检查以下函数以进行日期比较首先创建两个 NSDate 对象并传递给函数: 在 viewDidload 中或根据您的场景添加以下代码行。

      -(void)testDateComaparFunc{
      
      NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
      NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
      NSDateFormatter *dateFormatter=[NSDateFormatter new];
      [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
      NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
      NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
      BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}
      

      这里是函数

      -(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{
      
      BOOL isTokonValid;
      
      if ([date1 compare:date2] == NSOrderedDescending) {
          //"date1 is later than date2
          isTokonValid = YES;
      } else if ([date1 compare:date2] == NSOrderedAscending) {
          //date1 is earlier than date2
          isTokonValid = NO;
      } else {
         //dates are the same
          isTokonValid = NO;
      
      }
      
      return isTokonValid;}
      

      只需更改日期并测试上述功能:)

      【讨论】:

        猜你喜欢
        • 2013-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多