比较两个NSDates并忽略时间组件 [英] Comparing two NSDates and ignoring the time component
问题描述
比较两个NSDates最有效/推荐的方法是什么?我希望能够看到两个日期是否在同一天,无论时间如何,并且已经开始编写一些在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屋!