【发布时间】:2011-10-24 10:30:50
【问题描述】:
我试图将自 1970 年 1 月 1 日以来具有小时时区偏移量(即 -6)的时间戳(以秒为单位)转换为本地 NSDate。这是我目前所拥有的:
NSInteger startTime = 1312228800;
NStInteger startTimeOffset = -6;
NSDate *startTimeDate = [NSDate dateWithTimeIntervalSince1970:startTime];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZZ"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSInteger gmtOffset = [startTimeOffset intValue]*60*60;
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:gmtOffset]];
NSDate *newStartTimeDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:startTimeDate]];
例如,如果我有 1312228800 的时间,我会在 GMT 0 获得 08/01/2011 20:00。实际开始时间是 08/01/2011 14:00 GMT -6。但是,如果我位于 EST,则在本地设备上,startTime 应设置为 08/01/2011 16:00 GMT -4。
但是,在上面的示例中,我只是返回相同的 startTime,而没有考虑偏移量,即 08/01/2011 20:00。
我在这里出错的任何想法,感觉它与 setDateFormat: 参数有关?
谢谢
【问题讨论】:
-
执行最后一条语句之前的“startTime”是什么样的??
-
什么是“startTimeOffset”??
-
如果你最终得到一个 NSDate 对象,你为什么要关心时区?在格式化之前不会真正提供时区——NSDate 对象中的 TZ 仅供
description使用,它只能用于诊断格式化。 -
startTime 为 1312228800,startTimeOffset 为 -6。还更正了上面的示例以反映 newStartDate。我这样做的原因是尝试将 startTime 转换为我可以保存到 Core Data 的 NSDate 对象。当然,当我读取显示日期时我可以进行转换,但无论哪种方式都是同样的问题?
-
就像我说的,NSDate 对象中的时区是没有意义的。
标签: iphone ios nsdate nsdateformatter