[objective-c] iOS : 두 날짜 비교

나는이 NSDate내가 다른 두 사람과 함께 비교해야한다는 것을 NSDate나는 함께 노력 NSOrderAscending하고 NSOrderDescending있지만 내 날짜가 다른 두 날짜에 동일한 경우는?

예 : myDate = 24/05/2011 하나와 다른 두 개가 하나 = 24/05/2011및 두 개이면 24/05/2011무엇을 사용할 수 있습니까?



답변

Apple 문서에 따르면NSDate compare:

수신자와 다른 주어진 날짜의 시간적 순서를 나타내는 NSComparisonResult 값을 반환합니다.

- (NSComparisonResult)compare:(NSDate *)anotherDate

매개 변수 anotherDate

수신자를 비교할 날짜입니다. 이 값은 nil이 아니어야합니다. 값이 nil이면 동작이 정의되지 않으며 Mac OS X의 향후 버전에서 변경 될 수 있습니다.

반환 값

만약:

수신자와 anotherDate는 정확히 서로 동일합니다.
NSOrderedSame

수신자가 anotherDate보다 늦습니다.
NSOrderedDescending

수신자가 anotherDate보다 시간이 빠릅니다.
NSOrderedAscending

다시 말해:

if ([date1 compare:date2] == NSOrderedSame) ...

특정 경우에는 이것을 읽고 쓰는 것이 더 쉬울 수 있습니다.

if ([date2 isEqualToDate:date2]) ...

이것에 대한 Apple 문서를 참조하십시오 .


답변

stackoverflow와 웹을 많이 검색 한 후 가장 좋은 방법은 다음과 같다는 결론을 내 렸습니다.

- (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;
}

시간 차이로 변경할 수도 있습니다.

즐겨!


편집 1

날짜를 dd / MM / yyyy 형식으로 만 비교하려면 NSDate* currentdate = [NSDate date];&& 사이에 아래 줄을 추가해야합니다.NSTimeInterval distance

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];


답변

비교 함수에서 반환 값이 무엇인지 묻습니다.

날짜가 같으면 다음을 반환합니다. NSOrderedSame

오름차순 (2nd arg> 1st arg) 반환 NSOrderedAscending

내림차순 (2nd arg <1st arg) 반환 NSOrderedDescending


답변

이 질문을했는지 정확히 모르겠지만 NSDate의 날짜 구성 요소 만 비교하려면 NSCalendar 및 NSDateComponents를 사용하여 시간 구성 요소를 제거해야합니다.

이와 같은 것이 NSDate의 카테고리로 작동합니다.

- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];

    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
    return [selfDateOnly compare:otherDateOnly];
}


답변

NSDate실제로 참조 날짜 (제 생각에 2000 년 1 월 1 일 UTC) 이후의 시간 간격을 초 단위로 나타냅니다. 내부적으로 배정 밀도 부동 소수점 숫자가 사용되므로 임의의 두 날짜가 같은 날에 있더라도 동일하게 비교할 가능성이 거의 없습니다. 특정 날짜가 특정 날짜에 해당하는지 확인하려면을 사용해야 할 것입니다 NSDateComponents. 예 :

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 


답변

날짜 비교를 위해 다음 함수를 먼저 확인하십시오. 먼저 두 개의 NSDate 개체를 만들고 함수에 전달하십시오. viewDidload 또는 시나리오에 따라 코드의 다음 줄을 추가하십시오.

-(void)testDateComaparFunc{

NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}

여기에 기능이 있습니다

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    //"date1 is later than date2
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    //date1 is earlier than date2
    isTokonValid = NO;
} else {
   //dates are the same
    isTokonValid = NO;

}

return isTokonValid;}

날짜를 변경하고 위의 기능을 테스트하십시오 🙂


답변