2012-07-15 2 views
3

내가 다음 코드서식있는 NSDate 객체 내가 HH "로 날짜를 포맷 할

-(NSDate *)getCurrentDateinLocalTimeZone 
{ 
NSDate* sourceDate = [NSDate date]; 

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate]; 
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; 
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; 

NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 

return [dateFormatter dateFromString: [dateFormatter stringFromDate:destinationDate]]; 
} 

으로 내 응용 프로그램에서 다른 지점에서 사용자 시간대에 현재있는 NSDate를 얻을 시간대를 변경 : mm를 두 번째 방법의 출력이 1에있어서의 결과를 3 시간 시프트하는 경우 UI 목적은 그래서 다음의 방법을

-(NSString *)formatDate:(NSDate *)date 
{ 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
dateFormatter.dateFormat = @"HH:mm"; 
return [dateFormatter stringFromDate:date]; 
} 

을 사용하기 위해 ",,, 나만있는 NSDate의 포맷을하지 변경할 시간, 내가 뭘 잘못하고있어?

+0

첫 번째 루틴은 날짜의 서식을 지정/인쇄하지 않습니다. 그리고 왜 첫 번째 루틴에서 마지막 줄을 가지고 있습니까? 'destinationDate' 만 리턴하면됩니다. –

+0

출력의 마지막 3 줄을 사용하십시오 – ahmad

+0

첫 번째 루틴의 마지막 줄은 단순히 날짜를 char 형식으로 변환 한 다음 NSDate 형식으로 다시 변환합니다. NSDate 객체에 *** *** 형식 (또는 시간대)이 저장되어 있지 않습니다. –

답변

6

getCurrentDateinLocalTimeZone 메서드는 표준 시간대의 날짜를 조정하고 표준 시간대를 벗어나는 형식 문자열을 사용하여 형식을 지정하며 서식이 지정된 문자열을 다시 구문 분석합니다. 결과로 나타나는 NSDate은 UTC 시간대입니다 (+0000, 2012-07-15 16:28:23 +0000은 UTC 시간을 나타냄). formatDate: 메서드는 로컬 시간대에 대해 설정된 dateFormatter을 사용하여 다른 시간을 생성합니다. 당신은 정확한 시간을 얻기 위해 UTC를 사용하는 포맷을 설정해야 다음 formatDate: 방법에

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 

[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

를 교체합니다.

+0

나는 그것을 시도했지만 작동하지 않았다 ... 여기에 해결책의 결과가있다 2012-07-15 16:28:23 +0000 // 첫 번째 방법의 값 반환 2012-07-15 16:28 : 34.037 링크 Rassayl 테스트하기 [20642 : f803] 19:28 – ahmad

+0

@ahmad 나는 대답을 수정했다. 나는 이것이 더 잘 작동 할 것이라고 생각한다. – dasblinkenlight

+0

@ahmad - 첫 번째 루틴은 날짜 형식을 지정하지 않으며 표준 시간대를 조정하지 않습니다. 돌아 오는 NSDate 객체는 NSLog로 UTC로 시간을 표시합니다. –

관련 문제