[英]NSDate compare is not working well
我已经阅读了有关该主题的所有问题和答案以及所有教程,但是由于某种原因,它不适用于我。 总是向我显示两个日期是同一日期!
请有人帮我弄清楚,我只想检查一个是否大于另一个(包括日期和时间-不包括秒),或者是否相等。
这是我的代码:
- (BOOL)isEndDateIsBiggerThanCurrectDate:(NSDate *)checkEndDate
{
NSString *endd = [NSDateFormatter localizedStringFromDate:checkEndDate
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterShortStyle];
NSString *curreeeent = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterShortStyle
timeStyle:NSDateFormatterShortStyle];
NSDateFormatter * df = [[NSDateFormatter alloc]init];;
NSDate * newCurrent = [df dateFromString:endd];
NSDate * newEnd = [df dateFromString:curreeeent];
switch ([newCurrent compare:newEnd])
{
case NSOrderedAscending:
return YES;
break;
case NSOrderedSame:
return NO;
break;
case NSOrderedDescending:
return NO;
break;
}
}
非常感谢你!
为此,您必须使用NSCalender 。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit);
NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:[NSDate date]];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate: checkEndDate];
NSDate *first = [calendar dateFromComponents:firstComponents];
NSDate *second = [calendar dateFromComponents:secondComponents];
NSComparisonResult result = [first compare:second];
if (result == NSOrderedAscending) {
//checkEndDate is before now
} else if (result == NSOrderedDescending) {
//checkEndDate is after now
} else {
//both are same
}
您实际上应该使用时间间隔,而不是在日期和字符串之间进行转换。
类似以下内容应适合您的需求:
//current time
NSDate *now = [NSDate date];
//time in the future
NSDate *distantFuture = [NSDate distantFuture];
//gather time interval
if([now timeIntervalSinceDate:distantFuture] > 0)
{
//huzzah!
}
我得到了答案,只需检查两个日期之间的确切时间并进行比较即可。
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
为什么不将日期更改为自1970年以来的时间间隔,并按此排序。 数字比较极其简单,比字符串比较要快得多,而且它们始终会正确排序,而不像1,10,11,2,21,22,3,....
NSDate *now = [NSDate date];
NSTimeInterval ti = [now timeIntervalSince1970];
而已。 没有新的对象创建,更快,更少的CPU负担。
在这里查看如何摆脱秒数,但是这很容易,因为您有秒数。 请参阅此处如何将NSDate的秒设置为零
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.