我正在尝试修复的代码是:
if (!([key compare:todaysDate] == NSOrderedDescending))
{
todaysDateSection = [eventSectionsArray count] - 1;
}
其中key和todaysDate是NSDate对象,而todaysDate是使用以下方式创建的:
NSDate *todaysDate = [[NSDate alloc] init];
问候
Dave
if (!([key compare:todaysDate] == NSOrderedDescending))
{
todaysDateSection = [eventSectionsArray count] - 1;
}
其中key和todaysDate是NSDate对象,而todaysDate是使用以下方式创建的:
NSDate *todaysDate = [[NSDate alloc] init];
问候
Dave
我很惊讶其他答案没有提到获取对象的“开始日期”的选项:
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date2 interval:NULL forDate:date2];
这段代码将date1
和date2
设置为它们各自所在日期的开始时刻。如果它们相等,则意味着它们处于同一天。
或者选择以下代码:
NSUInteger day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit: forDate:date1];
NSUInteger day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date2];
这将设置day1
和day2
为可以进行比较的任意值。如果它们相等,那么它们就是在同一天。
在比较日期之前,将时间设置为00:00:00:
unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
// ... necessary cleanup
然后您可以比较日期值。请参阅参考文档中的概述。
iOS 8引入了一种新的方法,使得这个过程更加简单。
- (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit NS_AVAILABLE(10_9, 8_0);
您可以将粒度设置为关注的单位。这样会忽略其他所有单位,并将比较限制在所选单位中。
compareDate:toDate:toUnitGranularity:
在iOS >=8上的方法。然后,一旦你停止支持<8的OS版本,你就可以将实现压缩到只调用compareDate:toDate:toUnitGranularity:
。 - Duncan CdifferenceBetweenDate:andDate:usingUnit:
,它将返回负数、零或正整数值,表示所请求单位中日期之间的差异量。 - Duncan CiOS8及更高版本,检查两个日期是否在同一天的方法如下:
if NSCalendar.current.isDate(date1, inSameDayAs:date2) {
[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2]
请参阅文档
这是所有答案的速记:
NSInteger interval = [[[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: date1
toDate: date2
options: 0] day];
if(interval<0){
//date1<date2
}else if (interval>0){
//date2<date1
}else{
//date1=date2
}
-(NSDate*)normalizedDateWithDate:(NSDate*)date
{
NSDateComponents* components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate: date];
return [calendar_ dateFromComponents:components]; // NB calendar_ must be initialized
}
显然,您需要有一个名为calendar_
的实例变量,其中包含一个NSCalendar
对象。
使用此方法,可以轻松检查日期是否为今天:
[[self normalizeDate:aDate] isEqualToDate:[self normalizeDate:[NSDate date]]];
([NSDate date]
返回当前日期和时间。)
当然,这与Gregory提出的建议非常相似。这种方法的缺点是它往往会创建大量临时的NSDate
对象。如果你要处理大量的日期,我建议使用其他方法,如直接比较组件或使用NSDateComponents
对象而不是NSDates
。
-(NSInteger) daysBetweenDate:(NSDate *)firstDate andDate:(NSDate *)secondDate {
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *components = [currentCalendar components: NSDayCalendarUnit fromDate: firstDate toDate: secondDate options: 0];
NSInteger days = [components day];
return days;
}
NSCalendar *calendar = [NSCalendar currentCalendar];
NSComparisonResult dateComparison = [calendar compareDate:[NSDate date] toDate:otherNSDate toUnitGranularity:NSCalendarUnitDay];
针对使用Swift 3进行编码的开发人员
if(NSCalendar.current.isDate(selectedDate, inSameDayAs: NSDate() as Date)){
// Do something
}
在Swift 3中,根据您的需求,您可以选择以下两种模式之一来解决问题。
compare(_:to:toGranularity:)
方法Calendar
有一个叫做compare(_:to:toGranularity:)
的方法。 compare(_:to:toGranularity:)
的声明如下:
func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult
orderedSame
,否则可以是orderedAscending
或orderedDescending
。import Foundation
let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"
/* Compare date1 and date2 */
do {
let comparisonResult = calendar.compare(date1, to: date2, toGranularity: .day)
switch comparisonResult {
case ComparisonResult.orderedSame:
print("Same day")
default:
print("Not the same day")
}
// Prints: "Not the same day"
}
/* Compare date1 and date3 */
do {
let comparisonResult = calendar.compare(date1, to: date3, toGranularity: .day)
if case ComparisonResult.orderedSame = comparisonResult {
print("Same day")
} else {
print("Not the same day")
}
// Prints: "Same day"
}
dateComponents(_:from:to:)
Calendar
类有一个名为 dateComponents(_:from:to:)
的方法。该方法的声明如下:
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
返回两个日期之间的差异。
下面的 Playground 代码演示了如何使用它:
import Foundation
let calendar = Calendar.current
let date1 = Date() // "Mar 31, 2017, 2:01 PM"
let date2 = calendar.date(byAdding: .day, value: -1, to: date1)! // "Mar 30, 2017, 2:01 PM"
let date3 = calendar.date(byAdding: .hour, value: 1, to: date1)! // "Mar 31, 2017, 3:01 PM"
/* Compare date1 and date2 */
do {
let dateComponents = calendar.dateComponents([.day], from: date1, to: date2)
switch dateComponents.day {
case let value? where value < 0:
print("date2 is before date1")
case let value? where value > 0:
print("date2 is after date1")
case let value? where value == 0:
print("date2 equals date1")
default:
print("Could not compare dates")
}
// Prints: date2 is before date1
}
/* Compare date1 and date3 */
do {
let dateComponents = calendar.dateComponents([.day], from: date1, to: date3)
switch dateComponents.day {
case let value? where value < 0:
print("date2 is before date1")
case let value? where value > 0:
print("date2 is after date1")
case let value? where value == 0:
print("date2 equals date1")
default:
print("Could not compare dates")
}
// Prints: date2 equals date1
}
NSDayCalendarUnit
已被弃用,替换为NSCalendarUnitDay
。 - Dwayne Forde