2016-12-30 95 views
0

團隊,錯誤的轉換NSString到NSdate

當轉換NSString NSDate它給了我錯誤的結果。

NSDateFormatter * formatter = [NSDateFormatter new]; 
[formatter setDateFormat:@"yyyy-MM-dd"]; 
NSString * currentDateString = [formatter stringFromDate:[NSDate date]]; 
NSDate *currentDate = [formatter dateFromString:currentDateString]; 

currentDateString值是 「2017年1月1日」 的currentdate值越來越18:30:00 2016年12月31日+0000

有人驚喜,我是什麼東西錯在對話中?

+0

它返回UTC時間,所以我只好把它轉換成你的本地時間 –

+2

你需要包括時區信息的http:/ /stackoverflow.com/questions/1268509/convert-utc-nsdate-to-local-timezone-objective-c – Flexicoder

+0

您必須爲此設置timeZoneWithName屬性...... –

回答

1

問題是你還沒有添加日期格式化程序的時區。隨後一更新代碼:

NSDateFormatter * formatter = [NSDateFormatter new]; 
[formatter setDateFormat:@"yyyy-MM-dd"]; 
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
NSString * currentDateString = [formatter stringFromDate:[NSDate date]]; 
NSDate *currentDate = [formatter dateFromString:currentDateString]; 

現在值將

currentDateString = 「2016年12月30日」

的currentdate = 2016年12月30日00:00:00 +0000

+0

只有在您希望將日期字符串解釋爲UTC時間而不是本地時間時才執行此操作。 – rmaddy

1

用以下方法調用時區字符串,您希望日期&此方法將返回該特定時區的日期。

-(NSString *)getCurrentDateForTimeZone:(NSString *)timeZone{ 
    NSDate *currentDate = [[NSDate alloc] init]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:timeZone]];// Your timezone 
    NSString *localDateString = [dateFormatter stringFromDate:currentDate]; 
    return localDateString; 
} 

此方法將返回您已經通過的時區的當前日期。

編輯:如果用日期以及需要時間再修改dateFormatter到

[dateFormatter setDateFormat = @"yyyy-MM-dd hh:mm:ss a"]; // you can modify the format with the way you want