【问题标题】:How to convert timestamp in seconds with hour offset to local iOS NSDate?如何将带有小时偏移的时间戳以秒为单位转换为本地 iOS NSDate?
【发布时间】: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


【解决方案1】:

您需要使用格式化程序吗?像这样的东西呢:

NSInteger offsetSecs = [startTimeOffset intValue] * 60 * 60;
NSDate *theDate = [NSDate dateWithTimeIntervalSince1970:(startTime + offsetSecs)];

【讨论】:

  • 只有当设备/用户与偏移处于同一时区时才有效?
  • 然后要获取本地时间,使用手机上的当前时区调整上面的结果(即格林威治时间): NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; timeZoneOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]
猜你喜欢
  • 1970-01-01
  • 2015-06-17
  • 2019-03-03
  • 2011-07-08
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 2021-09-29
  • 2012-07-15
相关资源
最近更新 更多