2016-10-03 50 views
-1

dbVoiceDate不對,爲什麼?iOS NSDateFormatter返回錯誤日期

我試了很多!

NSDateFormatter *formatterVoice = [[NSDateFormatter alloc] init]; 
formatterVoice.dateFormat = @"dd-MMM-yyyy hh:mm:ss"; 
dbVoiceDate = [formatterVoice dateFromString:dbDateStr]; 

獲得響應:

dbDateStr的印刷描述:

03-Oct-2016 10:43:59 

self->dbVoiceDate印刷描述:

2016-10-03 05:02:16 +0000 

在此先感謝。

+0

時區是問題,請參閱http://stackoverflow.com/questions/16621330/nsdateformatter-not-working-to-set-settimezone –

+0

http://stackoverflow.com/questions/8442706/nsdateformatter-and -time-zone-issue –

+0

什麼樣的約會你不會告訴我..然後我給你完美的答案。 –

回答

1

格式像這樣

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MMM-yyyy hh:mm:ss"]; 
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; 

//then do your coding. 
0

您需要檢查時區。如果是在格林尼治標準時間設置時區爲GMT,像這樣:

[youDateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]; 

否則你可以使用本地時區是這樣的:

[youDateFormat setTimeZone:[NSTimeZone systemTimeZone]]; 

希望這有助於... :)

1

嘗試這一點: -

NSString *dateString = @"Thu Oct 3 10:34:58 +0000 2016"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"EEE MMM dd hh:mm:ss Z yyyy"]; 
NSDate *date = [dateFormatter dateFromString:dateString]; 
NSLog(@"%@", date); 
[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm:ss"]; 
NSString *finalDateStr = [dateFormatter stringFromDate:date]; 
NSLog(@"%@", finalDateStr); 
1

試試這個下面的代碼:

+(NSString*)getDateWithMonthSpelling:(NSString*)dateStr 
{ 
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; 
    dateFormatter.dateFormat = @"dd/MM/yyyy"; 
    NSDate *yourDate = [dateFormatter dateFromString:dateStr]; 
    dateFormatter.dateFormat = @"dd MMM yyyy"; 
    NSString*myDate = [dateFormatter stringFromDate:yourDate]; 
    return myDate; 
}