我有2 NSDates
,startdate
和enddate
。这些日期具有以下格式。
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
任何帮助?
答案 0 :(得分:1)
试试这个:
if ([event.startDate compare:event.endDate]==NSOrderedSame)
{
// The same
}
else
{
// Not the same
}
编辑:
现在我已经注意到了(@ trojanfoe的正确的评论):确保时间也相等,或者只是从NSDate
个对象中删除它。
答案 1 :(得分: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);
}