2016-11-21 2 views
0

NSString에서 NSDate 개체를 출력하려고하는 이상한 결과가 있습니다. NSString을 내 : 변환 할 1976년 6월 11일 내 방법은 다음과 같습니다NSString에서 NSDate로 변환하는 이상한 변환

-(NSDate*)dateFromString:(NSString *)dateString{ 

    // Convert string to date object 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *date = [dateFormat dateFromString:dateString]; 
    return date; 
} 

그러나 출력

1976-06-10 21:00:00 +0000가 어떻게 그런 일이 일어날 수 있을까? 1 일 차이.

+0

출력용으로 제공된 dateString은 무엇입니까? –

+0

시간대 문제입니다. NSDateFormatter에 시간대를 지정해보십시오. –

+1

차이는 하루가 아닌 3 시간입니다. 귀하의 시간대는 UTC + 3입니다. 'NSLog'는 항상 날짜를 UTC로 인쇄합니다. 날짜는 정확합니다. – vadian

답변

1

당신은 UTC 날짜와 현지 날짜 내로 UTC 날짜 문자열을 변환하는 방법을 다음 사용할 수 있습니다

- (NSDate *)convertIntoGMTZoneDate:(NSString *)dateString 
    { 
     NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc]init]; 
     [gmtFormatter setDateStyle:NSDateFormatterFullStyle]; 
     [gmtFormatter setTimeStyle:NSDateFormatterFullStyle]; 
     [gmtFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; 

     return [gmtFormatter dateFromString:dateString]; 
    } 

    - (NSDate *)convertIntoSystemZoneDate:(NSString *)dateString 
    { 
     NSDateFormatter *systemZoneFormatter = [[NSDateFormatter alloc]init]; 
     [systemZoneFormatter setDateStyle:NSDateFormatterFullStyle]; 
     [systemZoneFormatter setTimeStyle:NSDateFormatterFullStyle]; 
     [systemZoneFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

     return [systemZoneFormatter dateFromString:dateString]; 
    } 
2

UTC 형식의 날짜가 있습니다.

NSTimeInterval seconds; // assume this exists 
NSDate *ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds]; 

NSDateFormatter *utcFormatter = [[NSDateFormatter alloc] init]; 
utcFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"]; 
utcFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz"; 

NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init]; 
localFormatter.timeZone = [NSTimeZone timeZoneWithName:@"EST"]; 
localFormatter.dateFormat = @"yyyy.MM.dd G 'at' HH:mm:ss zzz"; 

NSString *utcDateString = [utcFormatter stringFromDate:ts_utc]; 
NSString *LocalDateString = [localFormatter stringFromDate:ts_utc]; 

을 또는 당신은 시간대 이름에 대한 하드 코딩 된 문자열을 방지하기 위해 [NSTimeZone defaultTimeZone]를 사용할 수 있습니다 현지 시간으로 날짜를 변환에이 코드를 사용합니다. 이 메서드는 기본 표준 시간대가 설정되지 않은 경우 시스템 표준 시간대를 반환합니다.

1
func dateFromString(dateString: String) -> NSDate { 
    // Convert string to date object 
    var dateFormat = NSDateFormatter() 
    dateFormat.dateFormat = "yyyy-MM-dd" 
    dateFormat.timeZone = NSTimeZone(name: "UTC") 
    var date = dateFormat.dateFromString(dateString)! 
    print(date) 
    return date 
} 

출력 : 1976년 6월 11일 0시 0분 0초 0000

+0

감사하지만 신속하지 않습니다. –

+1

대신에 이것을 사용하십시오 [dateFormat setTimeZone : [NSTimeZone timeZoneWithName : @ "UTC"]]]; – rvx

1

코드를 디버그하면 1 일 차이가 있지만 실행 후에는 실제 날짜를 찾을 수 있습니다.

그것은 나를 위해 일합니다. 나는 그것이 당신을 도울 것이라고 생각합니다. 감사합니다.