【问题标题】:Comparing certain components of NSDate?比较 NSDate 的某些组件?
【发布时间】:2011-03-16 20:45:40
【问题描述】:

如何仅比较 2 NSDates 的年月日分量?

【问题讨论】:

标签: iphone comparison nsdate


【解决方案1】:

下面是你的做法:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDate *firstDate = ...; // one date
NSDate *secondDate = ...; // the other date

NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:firstDate];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:secondDate];

NSDate *truncatedFirst = [calendar dateFromComponents:firstComponents];
NSDate *truncatedSecond = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [truncatedFirst compare:truncatedSecond];
if (result == NSOrderedAscending) {
  //firstDate is before secondDate
} else if (result == NSOrderedDescending) {
  //firstDate is after secondDate
}  else {
  //firstDate is the same day/month/year as secondDate
}

基本上,我们取两个日期,去掉它们的小时-分钟-秒位,然后将它们转换回日期。然后我们比较这些日期(不再有时间部分;只有一个日期部分),并查看它们之间的比较。

警告:在浏览器中输入但未编译。警告实现者

【讨论】:

    【解决方案2】:

    看看这个话题NSDate get year/month/day

    取出日/月/年后,您可以将它们作为整数进行比较。

    如果你不喜欢这种方法

    相反,你可以试试这个..

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy"];
    int year = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    [dateFormatter setDateFormat:@"MM"];
    int month = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    [dateFormatter setDateFormat:@"dd"];
    int day = [[dateFormatter stringFromDate:[NSDate date]] intValue];
    
    • 还有一种方式……

      NSDateComponents *dateComp = [calendar components:unitFlags fromDate:date];
      
      NSInteger year = [dateComp year];
      
      NSInteger month = [dateComp month];
      
      NSInteger day = [dateComp day];
      

    【讨论】:

    • 太棒了,我在某处读到它可能没有,但感谢您的验证。
    【解决方案3】:

    从 iOS 8 开始可以使用NSCalendar-compareDate:toDate:toUnitGranularity: 方法。

    像这样:

        NSComparisonResult comparison = [[NSCalendar currentCalendar] compareDate:date1 toDate:date2 toUnitGranularity:NSCalendarUnitDay];
    

    【讨论】:

    • 这应该是 iOS 8 或更高版本的公认答案。与其他答案相比,假设更少,更简洁。
    【解决方案4】:

    使用-[NSDate compare:] 方法 - NSDate Compare Reference

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      相关资源
      最近更新 更多