iOS 开发, NSDate 与 NSString 转换相差 8 个小时问题

2015-09-13 12:12:31 +08:00
 fhefh

服务器给的时间格式:
"Sun Sep 13 11:43:04 +0800 2015"

我的代码:

NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";

NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

NSDateFormatter *format = [[NSDateFormatter alloc] init];

format.dateFormat = @"EEE MMM dd HH:mm:ss z yyyy";

format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

format.timeZone = sourceTimeZone;

NSDate *date = [format dateFromString:timeString];

NSLog (@"date: %@", date );

打印结果:
date: 2015-09-13 03:43:04 +0000

相差了八个小时,昨晚到今天弄了好长时间都没有弄好~
求指点~

6454 次点击
所在节点    iOS
6 条回复
jianzong
2015-09-13 12:19:53 +08:00
不是 NSDate 与 NSString 转换的问题吧,字串跟打印结果的时区就是差了 8 小时。

后面的+0000 和+0800 是指时区。
painter
2015-09-13 12:24:01 +08:00
@jianzong 对 是因为时区的原因 不是转换的问题
wezzard
2015-09-13 12:28:47 +08:00
結果是正確的,一個是 GMT +8 一個是 UTC ,兩個時間是相等的。

你可以嘗試一下用兩個 NSDateFormatter ,一個用來完成 NSString -> NSDate 的轉換,一個用來完成 NSDate -> NSString 的轉換,第一個 NSDateFormatter 不要設置時區,因爲你的 date format 裏面已經提示了時區,第二個 NSDateFormatter 設置時區爲本地時區。
SeanChense
2015-09-13 12:35:50 +08:00
中国在东八区。
fhefh
2015-09-13 12:50:06 +08:00
NSString *timeString = @"Sun Sep 13 11:43:04 +0800 2015";

NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];

NSDateFormatter *format = [[NSDateFormatter alloc] init];

format.dateFormat = @"EEE MMM dd HH:mm:ss z yyyy";

format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

format.timeZone = sourceTimeZone;

NSDate *date = [format dateFromString:timeString];

NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSDate *localDate = [date dateByAddingTimeInterval:interval];

NSLog (@"date: %@", localDate );

已解决~ 3QS

参考: http://blog.csdn.net/diyagoanyhacker/article/details/7096612
zerh925
2015-09-13 13:13:08 +08:00
format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
@“ en_US ”是美国?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/220334

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX