【问题标题】:Set NSDates days to same value将 NSDates 天数设置为相同的值
【发布时间】:2016-12-09 09:49:29
【问题描述】:

我想比较 2 个特定的日子,但是,我想比较月份和年份,而不是天数。例如,我得到了一个日期,比如 2016-08-16,而另一个日期是 2016-08-10,我需要比较日期并得到相等,因为它们的月份是相等的。

因此,我需要一种方法使两个 NSDate 的天数相等,因此我需要将 2016-08-10 设置为 2016-08-00。之后我也可以修改第二个日期并进行比较。

我有简单的相等性代码剪辑器,但我想它也考虑天数和小时数等:

 if ([dateOld compare:dateNew] == NSOrderedDescending) {
        NSLog(@"date1 is later than date2");
    } else if ([dateOld compare:dateNew] == NSOrderedAscending) {
        NSLog(@"date1 is earlier than date2");
    } else {
        NSLog(@"dates are the same");
    }

为了使其工作,我需要将 NSDates 的天数和时间“归零”。有什么办法吗?

【问题讨论】:

标签: ios objective-c nsdate


【解决方案1】:

看到这个答案:Comparing certain components of NSDate?

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (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 month/year as secondDate
}

【讨论】:

  • @A O 好的,我一会儿试试
  • NSMonthCalendarUnitNSYearCalendarUnit
  • 答案几乎相同。最好将问题标记为重复问题,并在特殊情况下使用 NSCalendarUnit 标志对其进行评论。
【解决方案2】:

如果你有两个日期,

NSDate *now = // some date
NSDate *other = // some other date

你可以这样比较:

if ([[NSCalendar currentCalendar] compareDate:now toDate:other toUnitGranularity:NSCalendarUnitMonth] == NSOrderedSame) {
    NSLog(@"Same month");
} else {
    NSLog(@"Different month");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多