问题
I have this code:
NSComparisonResult compareStart = [firstDate compare: dateSelected];
NSComparisonResult compareEnd = [secondDate compare: dateSelected];
if (((compareStart == NSOrderedAscending) || (compareStart == NSOrderedSame))
&& (compareEnd == NSOrderedDescending))
but it don't entry in the "if" when firstDate = dateSelected or secondDate = dateSelected...why??
回答1:
Are you sure that when firstDate equals dateSelected that date selected is earlier than secondDate? Currently your logic is: firstDate <= dateSelected < secondDate. If you want firstDate <= dateSelected <= secondDate, then you need to implement the code as follows:
NSComparisonResult compareStart = [firstDate compare: dateSelected];
NSComparisonResult compareEnd = [secondDate compare: dateSelected];
if ( (compareStart == NSOrderedAscending || compareStart == NSOrderedSame)
&& (compareEnd == NSOrderedDescending || compareEnd == NSOrderedSame)) {
// some code
}
Update:
To compare two NSDates without relying on time see: Comparing two NSDates and ignoring the time component
来源:https://stackoverflow.com/questions/6250383/date-in-a-specific-range-with-nsorderedascending-and-nsordereddescending