2011-03-29 41 views
1

我有我想從解析時間的字符串:錯誤的時間從NSDateFormatter

NSString *longdate = @"Mar 27, 2011 8:38:38 PM"; 

我要分析此日期和輸出只是時間部分瓦特/小時+分+ AM/PM:

// First, convert our string into an NSDate 
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init]; 
[inFormat setDateFormat:@"MMM dd, yyyy HH:mm:ss aaa"]; 
NSDate *date = [inFormat dateFromString:longdate]; 
[inFormat release]; 

// Now convert from date back to a string 
NSDateFormatter *outFormat = [[NSDateFormatter alloc] init]; 
[outFormat setDateFormat:@"HH:mm aaa"]; 
NSString *final = [outFormat stringFromDate:date]; 
[outFormat release]; 

NSLog(@"original: %@ | final %@", longdate, final); 

問題是最後的時間是錯誤的。我預計時間是晚上8點38分,但我會在下午12點38分。

我只想得到相同的時間,我把它,而不是打擾W /任何時區或地區。我在這裏做錯了什麼?謝謝。

回答

6

發現此問題。與時區和所有與日期格式化程序使用錯誤格式代碼有關的內容無關。

[inFormat setDateFormat:@"MMM dd, yyyy HH:mm:ss aaa"]; 

應該是:

[inFormat setDateFormat:@"MMM dd, yyyy h:mm:ss aaa"]; 

同樣,outFormat的日期格式應該是:

[outFormat setDateFormat:@"h:mm aaa"]; 

調整過後一切正常,甚至W/O任何時區調整。

0

你有你的時區搞砸了。 IIRC,NSDateFormatter(默認情況下)將解析UTC時區(+000)中的內容,但在當前時區內日期爲NSLog。或類似的東西。

無論如何,請檢查您的時區。

1

正如戴夫所說,檢查您的時區。您可以告訴日期格式化程序以使用您當前的時區以及:

[outFormat setTimeZone:[NSTimeZone localTimeZone]]; 
-1
NSString *longdate = @"2013-04-29 10:20 PM"; 

// First, convert our string into an NSDate 
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init]; 
[inFormat setTimeZone:[NSTimeZone localTimeZone]]; 
[inFormat setDateFormat:@"yyyy-MM-dd hh:mm aa"]; 
NSDate *date = [inFormat dateFromString:longdate]; 

// Now convert from date back to a string 
NSDateFormatter *outTimeFormat = [[NSDateFormatter alloc] init]; 
[outTimeFormat setDateFormat:@"hh:mm aaa"]; 
NSString *finalTime = [outTimeFormat stringFromDate:date]; 


NSDateFormatter *outDateFormat = [[NSDateFormatter alloc] init]; 
[outDateFormat setDateFormat:@"yyyy-MM-dd"]; 
NSString *finalDate = [outDateFormat stringFromDate:date]; 

NSLog(@"Date:%@ and Time :%@",finalDate,finalTime);