我已经阅读了所有问题和答案以及有关此主题的所有教程,但由于某种原因,它不适合我。总是告诉我两个日期是相同的日期!
请有人帮我弄明白,我只是想检查一个人是否比另一个人大(包括日期和时间 - 没有秒数)或是否相等。
这是我的代码:
- (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;
}
}
非常感谢!
答案 0 :(得分:1)
为此,您必须使用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
}
答案 1 :(得分:0)
您应该使用时间间隔,而不是在日期和字符串之间进行转换。
以下内容应符合您的需求:
//current time
NSDate *now = [NSDate date];
//time in the future
NSDate *distantFuture = [NSDate distantFuture];
//gather time interval
if([now timeIntervalSinceDate:distantFuture] > 0)
{
//huzzah!
}
答案 2 :(得分:0)
我得到了答案,只是检查两个日期之间的确切时间并进行比较。
- (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;
}
答案 3 :(得分:-2)
为什么不将日期更改为自1970年以来的时间间隔并按此排序。非常简单的数字比较,比字符串比较快得多,并且它们总是排序正确,而不是像1,10,11,2,21,22,3 ...... ....
NSDate *now = [NSDate date];
NSTimeInterval ti = [now timeIntervalSince1970];
多数民众赞成。没有新的对象创建,更快,更少的CPU负担。
请看这里你如何摆脱秒,但这很简单,因为你有数字,几秒钟。见How to set seconds to zero for NSDate