2012-10-27 2 views
0

두 개의 NSDate 개체가 같은 연도/월/일이지만 다른 시간대에 있는지 테스트하고 싶습니다.NSDateComponents를 사용하여 시간이 다를 때 날짜 동등성 검사

NSDate *date1 = [dataDictionary1 valueForKey:@"date"]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.timeZone = [NSTimeZone systemTimeZone]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1]; 
NSDate *newDate1 = [calendar dateFromComponents:components]; 

NSDate *date2 = [dataDictionary2 valueForKey:@"date"]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.timeZone = [NSTimeZone systemTimeZone]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date2]; 
NSDate *newDate2 = [calendar dateFromComponents:components]; 

그러나, newDate12012-05-01 04:00:00 +00002012-05-01 05:00:00 +0000newDate2로 반환 : 여기 내 코드입니다.

시간대가 GMT가 아니기 때문에 시간이 0이 아니지만 왜 2 시간이 같지 않습니까? 시간이 다른 날짜가 같은지 테스트하는 더 좋은 방법을 알고 있습니까? (즉, 각각의 날짜 구성 요소를 받고 각 일/월/년 평등을 테스트하는 것보다 효율적이다?)

답변

0

이 시도 : 물론

NSDate *date1 = [dataDictionary1 valueForKey:@"date"]; 
long noTime1 = [date1 timeIntervalSinceReferenceDate]/(60*60*24); 

NSDate *date2 = [dataDictionary2 valueForKey:@"date"]; 
long noTime2 = [date2 timeIntervalSinceReferenceDate]/(60*60*24); 

if (noTime1 == noTime2) { 
    // same date 
} 

이 유일한 작품이 단순히 비교하려는 경우 실제 날짜, 월 또는 연도 값은 신경 쓰지 않습니다.

+0

감사합니다. rmaddy. 정말 깨끗합니다. 이 특별한 경우에는 하루 정보가 필요하지만,이 프로젝트에서 답이 매우 유용 할 다른 지점이 있습니다 :) – kiks