2015-11-24 37 views
-1

我使用的代碼相同的這個最佳答案轉換的NSString的NSDate不工作

Converting NSString to NSDate (and back again)

NSString *dateString = @"01-02-2010"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
// this is imporant - we set our input date format to match our input string 
// if format doesn't match you'll get nil from your string, so be careful 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
// voila! 
dateFromString = [dateFormatter dateFromString:dateString]; 

但dateFromString結果2010-01-31 17:00:00 +0000 爲什麼不一樣天。
我無法比較日期。因爲當前時區的

回答

0

它,添加此然後將要給你正確的日期

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; 
0

添加以下行就在你設置的日期格式後。這是因爲它會默認使用設備的本地時區進行轉換。這個對我有用!

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
0

它實際上是相同的日期。但日期格式化程序默認情況下會在設備的本地時區中解析日期字符串(如果未傳入時區)。在您的情況下,您的日期被解釋爲Midnight 2010年2月2日UTC + 7即2010年1月31日17: 00 UTC。

如果日期字符串總是在UTC,通過在UTC時區到日期格式是這樣的:

NSString *dateString = @"01-02-2010"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
// this is imporant - we set our input date format to match our input string 
// if format doesn't match you'll get nil from your string, so be careful 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSDate *dateFromString = [[NSDate alloc] init]; 
// voila! 
dateFromString = [dateFormatter dateFromString:dateString];