比较NSDate的某些组件? [英] Comparing certain components of NSDate?

查看:107
本文介绍了比较NSDate的某些组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何只比较2 NSDates

推荐答案

因此,您可以这样做:

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
}


$ b b

基本上,我们把这两个日期,砍掉他们的小时 - 分秒秒位,并把它们变回日期。然后我们比较那些日期(不再有时间组件;只有日期组件),并看看它们如何与彼此比较。

Basically, we take the two dates, chop off their hours-minutes-seconds bits, and the turn them back into dates. We then compare those dates (which no longer have a time component; only a date component) and see how they compare to eachother.

警告:浏览器而不是编译。 Caveat实施者

这篇关于比较NSDate的某些组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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