比较两个 NSDates 并忽略时间分量 [英] Comparing two NSDates and ignoring the time component

查看:38
本文介绍了比较两个 NSDates 并忽略时间分量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较两个 NSDate 的最有效/推荐的方法是什么?我希望能够查看两个日期是否在同一天,无论时间如何,并且已经开始编写一些使用 NSDate 类中的 timeIntervalSinceDate: 方法并获取此值的整数除以秒数的代码一天内.这似乎很冗长,我觉得我错过了一些明显的东西.

What is the most efficient/recommended way of comparing two NSDates? I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day. This seems long winded and I feel like I am missing something obvious.

我试图修复的代码是:

if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}

其中 key 和 todaysDate 是 NSDate 对象,而 todaysDate 正在使用:

where key and todaysDate are NSDate objects and todaysDate is creating using:

NSDate *todaysDate = [[NSDate alloc] init];

问候

戴夫

推荐答案

你在做比较之前将日期中的时间设置为 00:00:00:

You set the time in the date to 00:00:00 before doing the comparison:

unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date];

NSDate* dateOnly = [calendar dateFromComponents:components];

// ... necessary cleanup

然后您可以比较日期值.请参阅参考文档中的概述.

Then you can compare the date values. See the overview in reference documentation.

这篇关于比较两个 NSDates 并忽略时间分量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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