两个NSDate之间的日期比较

Ale*_*lom 1 date objective-c nsdate ios

这是我第一次比较Objective-C中的日期.我一直在网上搜索一段时间,我发现的所有例子都涉及从字符串构建一个NSDate,所以我决定在这里问一个新问题......我的问题如下:

我需要知道两个NSD是否在同一天,忽略了时间.我有两个NSArray包含一组日期,我需要逐个确定第一个NSArray中的哪一个与第二个数组在同一天.

- (void)setActiveDaysColor:(UIColor *)activeDaysColor
{
    for (DayView *actualDay in _days)
    {
        NSDate *actualDayDate = [actualDay date];

        for (NSDate *activeDayDate in self.dates)
        {
            // Comparison code
            // If both dates are the same, tint actualDay with a different color
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

提前谢谢你,祝你有个愉快的一天.

亚历克斯.

Vik*_*ica 10

通过省略时间组件来创建新日期.并使用其中一种比较方法

例

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger components = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDateComponents *firstComponents = [calendar components:components fromDate:firstDate];
NSDateComponents *secondComponents = [calendar components:components fromDate:secondDate];

NSDate *date1 = [calendar dateFromComponents:firstComponents];
NSDate *date2 = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
}
Run Code Online (Sandbox Code Playgroud)