2016-08-27 137 views
0

我從服務器獲取UTC時間字符串爲「2016/8/27 6:56:23」無法將UTC時間轉換爲當地時間?

我需要將此日期轉換爲我的本地時區。

NSString *dateFormat = @"dd/MM/yyyy HH:mm:ss a"; 
NSTimeZone *inputTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init]; 
[inputDateFormatter setTimeZone:inputTimeZone]; 
[inputDateFormatter setDateFormat:dateFormat]; 

**NSDate *date = [inputDateFormatter dateFromString:_strLiveStreamStartTime];** 

NSTimeZone *outputTimeZone = [NSTimeZone localTimeZone]; 
NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init]; 
[outputDateFormatter setTimeZone:outputTimeZone]; 
[outputDateFormatter setDateFormat:dateFormat]; 
NSString *outputString = [outputDateFormatter stringFromDate:date]; 

NSLog(@"%@",outputString); 

問題是,當我將服務器字符串轉換成日期它給了我空值。 請幫我解決這個問題。我谷歌並實施一些解決方案,但無法得到。

回答

1

你的字符串是month/day...,你的日期格式是day/month...,這就是問題所在。 對於12小時模式,小時應該用小寫字母hh表示。

NSString *dateFormat = @"MM/dd/yyyy hh:mm:ss a"; 
+0

其實問題也與小時候的同伴有關。在HH:mm:ss中不工作,在12小時內合成工作。背後的任何具體原因。 –

+0

不,實際的問題是倒置的日/月順序。 'HH'工作在12小時模式,但hh'不在24小時模式,如果小時> 12。使用指定的說明符只是很好的編程習慣。 – vadian

相關問題