0

NSDateComponents 및 NSDateFormatter에서 이상한 결과가 나타납니다.NSDateComponent에서 잘못된 NSDate 가져 오기 2011-01-01

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd"];  
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2010-12-31"]]; 
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-01"]]; 
[MyUtils getTenOClockOnDate:[dateFormatter dateFromString:@"2011-01-02"]]; 

에만 두 번째 줄, 나는 예기치을 얻을 :

나는 다음과 같은 통화를하는 동안

+ (NSDate *)getTenOClockOnDate:(NSDate*)inputDate 
{ 

NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; 

NSDateComponents *components = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:inputDate]; 

[components setHour:10]; 
[components setMinute:0]; 
[components setSecond:0]; 

// construct new date and return 
NSDate *newDate = [cal dateFromComponents:components]; 

NSLog(@"input date: %@ -- new date: %@", inputDate, newDate); 

return newDate; 
} 

지정된 날짜의 오전 10시 시간을 설정하려면 다음 방법을 결과 :

input date: 2010-12-31 05:00:00 GMT -- new date: 2010-12-31 15:00:00 GMT 
input date: 2011-01-01 05:00:00 GMT -- new date: 2011-12-31 15:00:00 GMT 
input date: 2011-01-02 05:00:00 GMT -- new date: 2011-01-02 15:00:00 GMT 

문제는 두 번째 기록 인 2011-01-01에서 2로 바뀝니다. 011-12-31 그냥 시간을 10으로 설정하면됩니다.

답변

0

참으로 이상한 것처럼 보입니다. 코드가 잘 보이는 것처럼 보이지만 내 직감은 NSDateComponents을 초기화 할 때가 될 것입니다. NSHourCalendarUnitNSMinuteCalendarUnit을 사용할 수 없습니다.

당신은 이것이 필요하지 않을 것이라고 생각하지만, 비슷한 문제가 있다고 생각하고 날짜가 올바르게 수정되고 결과를 얻는 데 필요한 것으로 나타났습니다.

그래도 작동하지 않으면 캘린더의 시간대 설정이 필요할 수 있습니다. 이는 내가하는 일과 유일한 차이점이며 매력을 발휘하는 것 같습니다.

+1

에 너무 nslog 신청 같아요. –

+0

아, 잘 찾아 냈어! 나는 그것도 간과했다. – sradforth

0

이 NSDateComponents 오른쪽에서있는 NSDate 가치를 제공합니다

NSDateFormatter* df = [[NSDateFormatter alloc]init]; 
[df setDateFormat:@"yyyy-MM-dd"]; 
NSDate* date = [df dateFromString:@"2011-01-01"]; 
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:date]; 
NSInteger day = [components day];  
NSInteger month = [components month]; 
NSInteger year = [components year]; 
[df release]; 

NSLog(@"Day : %d, Month : %d, Year : %d",day,month,year); 

그것은 당신이 도움이 될 것입니다. 스위프트의

1

Println(date)가 잘못된, stringfromdate

nsdateformatter을 사용 나는 이것이`NSDayCalendarUnit`가 작동하게 사용 오브젝티브 C

관련 문제