두 날짜 사이의 날짜 수를 얻으 려하고 논리가 일정 기간 (2012 년 8 월 12 일 ~ 8 월 12 일)에 잘 작동하는 것으로 보입니다 - 364 계산에 마지막 날을 포함하면 365 일입니다. 그러나 2013 년 8 월 8 일부터 2013 년 8 월 12 일까지 플러그인하면 계산이 끝나는 날에 0이나 1이됩니다. 내가 잘못 여기서 뭐하는 거지 확실하지 무엇을 :목표 -C 날짜 차이 혼동
NSString* strNow = @"August 12, 2013";
NSString* strThen = @"August 8, 2012";
NSString* strNumOfDays = [dateManager getDateDifference:strThen :strNow];
방법
- (NSString*) getDateDifference : (NSString*) startDate : (NSString*) endDate {
//convert strings to dates
NSDate* dateStart = [self convertStringToDate:startDate];
NSDate* dateEnd = [self convertStringToDate:endDate];
//check to make sure the second date is later than the first
//get the number of days between
NSCalendar* gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [gregorianCalendar components:NSDayCalendarUnit fromDate:dateStart toDate:dateEnd options:0];
//the plus one is for including the endDate in the count
return [NSString stringWithFormat:@"%i", [components day]+1];
}
변환 문자열을 날짜 방법
- (NSDate*) convertStringToDate : (NSString*) strToConvert {
NSError* error = nil;
NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeDate error:&error];
NSArray* arrDateMatches = [detector matchesInString:strToConvert options:0 range:NSMakeRange(0, [strToConvert length])];
for (NSTextCheckingResult* match in arrDateMatches) {
strToConvert = [self convertDateToString:match.date];
}
NSDate* myDate = [dateFormatter dateFromString:strToConvert];
return myDate;
}
@Wain을 - 예상대로 변환이 노력하고 있습니다. @Rob - NSTextCheckingTypes를 사용하고 있는데 날짜를 제출할 형식을 알지 못해서 (2012 년 8 월 8 일, 2013 년 8 월 8 일, 2013 년 8 월 12 일 등)
'convertStringToDate'의 출력과 발생하는 오류를 확인하고 있습니까? – Wain