ios - 比较两个 NSDate 对象是否相同

标签 ios objective-c

下面是我的对比代码:

 int countTrue = 0;
 //NSDate *datee = [[self.reminderResultsArray objectAtIndex:0] date];

for(int i = 0; i < self.reminderResultsArray.count; i++){
    if([[NSCalendar currentCalendar] isDate:self.actualSelectedDate inSameDayAsDate:[[self.reminderResultsArray objectAtIndex:i] date]]){
        countTrue++;
        NSLog(@"Count true: %d", countTrue);
    } 
}

下面是我的self.reminderResults.array中的数据:

(lldb) po [[self.reminderResultsArray objectAtIndex:1] date] 2017-06-02 09:38:35 +0000

(lldb) po [[self.reminderResultsArray objectAtIndex:0] date] 2017-05-27 09:37:48 +0000

(lldb) po [[self.reminderResultsArray objectAtIndex:1] date] 2017-06-02 09:38:35 +0000

(lldb) po [[self.reminderResultsArray objectAtIndex:2] date] 2017-06-02 10:09:48 +0000

(lldb) po [[self.reminderResultsArray objectAtIndex:3] date] 2017-06-02 10:12:30 +0000

(lldb) po [[self.reminderResultsArray objectAtIndex:4] date] 2017-06-03 08:49:33 +0000

我的 self.actualSelectedDate 值为:

po self.actualSelectedDate
2017-06-02 16:00:00 +0000

按理说,countTrue 值应该是 3,但它只返回值 1。我的代码有什么问题吗?

最佳答案

如果您观察日志,那么时间是不同的,并且由于 NSCalender 方法会将它们视为不同的日期。

如果您只想进行日期比较,那么首先使用日期格式化程序 dd/mm/yyyy 创建日期对象,然后比较日期。

或者您可以检查日期、月份和年份部分

+ (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2 {
    NSCalendar* calendar = [NSCalendar currentCalendar];

    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |      NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

    return [comp1 day]   == [comp2 day] &&
    [comp1 month] == [comp2 month] &&
    [comp1 year]  == [comp2 year];
}

关于ios - 比较两个 NSDate 对象是否相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343110/

相关文章:

iphone - 如何在 IOS 6 中获取此背景条?

objective-c - 平移/滑动 View ,如相机锁屏

ios - 保留 View Controller 的计数

ios - 尝试在 iOS 中验证电子邮件,崩溃不知道为什么?

ios - 如何通过 firebase 中的嵌套值获取键名?

ios - 如何保存应用程序状态并再次恢复它

ios - 为什么这只将数组中的最后一个值插入到核心数据中

ios - 使用 swift 将当前用户的消息列表保存在解析中

ios - 有没有办法保证 iOS 应用程序关闭时某些代码的运行?

ios - 子类化 UICollectionViewCell 并从 xib 初始化