简体   繁体   English

如何将带有小时偏移量的时间戳(以秒为单位)转换为本地 iOS NSDate?

[英]How to convert timestamp in seconds with hour offset to local iOS NSDate?

Im trying to convert a timestamp in seconds since 01/01/1970 with an hour timezone offset (ie -6) to a local NSDate.我试图将自 1970 年 1 月 1 日以来的时间戳(以秒为单位)转换为具有小时时区偏移量(即 -6)的本地 NSDate。 Here is what i have so far:这是我到目前为止所拥有的:

    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]];

For example if i have the time of 1312228800 i get 08/01/2011 20:00 at GMT 0. The actual startTime is 08/01/2011 14:00 at GMT -6.例如,如果我有 1312228800 的时间,我会在 GMT 0 获得 08/01/2011 20:00。实际的开始时间是 08/01/2011 14:00 在 GMT -6。 However locally on the device if i am based in EST the startTime should be set to 08/01/2011 16:00 GMT -4.但是,如果我位于美国东部标准时间,则在本地设备上,startTime 应设置为 08/01/2011 16:00 GMT -4。

However i just get back the same startTime with no offset taken into account which is 08/01/2011 20:00 in the example above.但是,我只是返回相同的 startTime,没有考虑偏移量,在上面的示例中是 08/01/2011 20:00。

Any ideas where im going wrong here, have a feeling its got something to do with the setDateFormat: argument?我在这里出错的任何想法,感觉它与 setDateFormat: 参数有关吗?

thx谢谢

Do you need to use a formatter?你需要使用格式化程序吗? What about something like this:像这样的东西怎么样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM