0

我有一个 2 NSDates,一个startdateenddate。这些日期具有以下格式。

startDate = 2013-02-22 12:00:00 +0000; endDate = 2013-02-25 13:00:00 +0000;

现在我想比较这些日期。因此我有这个代码。

if([event.startDate isEqualToDate:event.endDate]){
     NSLog(@"event %@ is in the same day",event.title);
}else{
     NSLog(@"event %@ is NOT in the same day",event.title);
}

但问题是它总是出现在 else 语句中。我希望如果 startDate 和 endDate 在同一天、同一个月和同一年,他们给我第一个NSLog,否则他们给我第二个NSLog

有什么帮助吗?

4

2 回答 2

1

尝试这个 :

if ([event.startDate compare:event.endDate]==NSOrderedSame)
{
    // The same
}
else
{
    // Not the same
}

编辑: 现在我已经注意到(@trojanfoe 的正确评论):确保时间也相等,或者只是将其从您的NSDate对象中删除。

于 2013-02-13T08:32:29.890 回答
0
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *startDateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:startDate];
    NSDateComponents *endDateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:endDate];
    NSDate *startDate = [calendar dateFromComponents:startDateComponents];
    NSDate *endDate = [calendar dateFromComponents:endDateComponents];

    if([startDate isEqualToDate:endDate])
    {
        NSLog(@"event %@ is in the same day",event.title);
    }
    else{
        NSLog(@"event %@ is NOT in the same day",event.title);
    }
于 2013-02-13T08:39:23.063 回答