在设备时区中显示时间戳的正确方法是什么?

What is the correct way of showing a timestamp in device timezone?

我有这个时间戳:1439353372

This was generated when one of our user (from Canada) sent me a message (in India).

在我们的应用程序中 – 他看到了该消息的后续时间:2015-08-11 / 22:22pm,我看到了这个 2015-08-12 / 09:52am。他在他的 iPhone6 中看到了这个,而我在 iPhone6+ 模拟器上。

我认为这次是错误的 – 我对这个 timestamp/timezone 和日期转换有很多困惑。

下面是我们将时间戳转换为日期并以上述格式显示的代码。

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1439353372];
NSString *strDate = [df stringFromDate:date];
[df setDateFormat:@"HH:mm a"];
NSString *strTime = [df stringFromDate:date];
NSLog(@"%@",[NSString stringWithFormat:@"%@ / %@", strDate, strTime]);

我不确定这是显示用户所在地区特定时间戳日期的正确方式吗?

我应该在上面的代码中添加什么,以便它始终根据我们的设备时区向我们显示正确的时间?

创建时间戳时,添加本地时区:-

NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimezone: localTimeZone];

在检索时间戳时,执行相同的方法,以便根据您的时区获得正确的日期和时间。

已编辑:-

这是将时区添加到日期戳的方法,刚从这个 Source 中找到它,因为我现在没有时间编写代码

   NSDate* referenceDate = [NSDate dateWithTimeIntervalSince1970: 0];
   NSTimeZone* timeZone = [NSTimeZone systemTimeZone];
   int offset = [timeZone secondsFromGMTForDate: referenceDate];
   int current = unix_timestamp - offset;

好的,我发现,上面的日期和时间是正确的。在格林威治标准时间,如果将上述时间戳转换为 NSDate,您将得到以下结果:2015-08-12 / 04:22pm。因此,加拿大时区是 GMT-6(比 2015-08-12 / 04:22pm 时间早 6 小时),印度是 GMT+5.30(比 2015-08-12 / 04:22pm 时间早 5.30 小时)。所以我问的问题的结果似乎是纯粹的:)