2017-05-23 2 views
0

스웨덴에서이 코드를 실행할 때 UTC 표준 시간대의 datetime을 변환하는 데 이상한 문제가 있습니다. 내 변환 기능 내부dateFormatter가 스웨덴에서 NSDate를 nil로 반환합니다.

NSString* utcDateTime = @"5/23/2017 4:34 AM"; 
NSString* localTimeNSString = [self convertUTCDateTimeToLocal:utcDateTime]; 
NSLog(@"localTime:%@", localTimeNSString); 

는있는 NSDate에이 날짜를 구문 분석하는 나의 시도는 nil을 반환

- (NSString*)convertUTCDateTimeToLocal:(NSString*)theUTCDateTime 
{ 
    NSString* localTime = nil; 

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 

    if (dateFormatter) { 
     [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 

     // parse the passed parameter, theUTCDateTime, which looks like this: "05/23/2017 04:34 AM" 
     // Even though this date/time doesn't LOOK like a UTC-formatted timestamp, it is in the UTC timezone 

     [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"]; 
     NSDate* utcTime = [dateFormatter dateFromString:theUTCDateTime]; 

     // in Sweden, dateFormatter will return utcTime as nil. Not so in the United States or England. 
     // In the US, NSLog of utcTime is "2017-05-23 04:34:00 +0000" 

     // Now that we've parsed into an NSDate, display date & time the way the user's system is configured 
     // Of course, if utcTime is nil, then so is localTime (below) 
     [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
     dateFormatter.dateStyle = NSDateFormatterShortStyle; 
     dateFormatter.timeStyle = NSDateFormatterShortStyle; 
     localTime = [dateFormatter stringFromDate:utcTime]; 

     // in the US, dateFormatter will return localTime as "5/22/17, 9:34 PM" 
    } 

    return localTime; 
} 
+0

감사합니다. 죄송합니다 - 습관의 힘 (Objective-C++의 일부인 코드베이스이지만 C++ 언어 문제가 아님) – SMGreenfield

답변

1

NSDateFormatter 현재 로케일을 사용합니다. 미국 형식으로 날짜를 인식하려면 포맷터의 로켈을 미국 로켈로 설정하십시오.