使用特定时区将NSDate转换为Unix时间戳 [英] Convert an NSDate to a Unix timestamp using a particular time zone

查看:241
本文介绍了使用特定时区将NSDate转换为Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用特定时区获取Unix时间戳(不一定与系统时区相同)

I am trying to get the Unix timestamp using a particular time zone (not necessarily the same time zone as the system)

我尝试过:

 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithName:@"Australia/Melbourne"];
[dateFormatter setTimeZone:gmt];
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
NSDate *curdate = [dateFormatter dateFromString:timeStamp];

int unix_timestamp =  [curdate timeIntervalSince1970];

这显然应该在澳大利亚给出Unix时间戳但是,当我记录 curdate 时,它仍然是GMT的时间, timeStamp 是澳大利亚/墨尔本的时间。

This should apparently, give the Unix timestamp (up to seconds) in Australia. However, when I log curdate, its still the time in GMT, timeStamp being the time in Australia/Melbourne.

这里有什么问题?

推荐答案

code> timeIntervalSince1970 返回自1970年1月1日午夜起在GMT时间内的秒数。

The method timeIntervalSince1970 returns the number of seconds since midnight on January 1, 1970 in GMT time.

如果您想要从1970年1月1日午夜墨尔本开始计算的秒数,您只需要确定1970年1月1日墨尔本GMT的偏移量。

If you want the number of seconds since Jan 1, 1970 at midnight Melbourne time, you just need to determine what offset from GMT Melbourne was at, on Jan 1, 1970.

为此,您可以使用您的NSTimeZone实例

   NSDate* referenceDate = [NSDate dateWithTimeIntervalSince1970: 0];
   NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Australia/Melbourne"];
   int offset = [timeZone secondsFromGMTForDate: referenceDate];
   int melbourneTimestamp = unix_timestamp - offset;

或者,最后一行应该是 plus 只是测试代码,看看。我现在不在我的Mac。

Or, maybe the last line should be plus offset. Just test the code and see. I'm not on my Mac right now.

编辑:请参阅下面的Ayush的评论。聊天后,看起来该偏移是添加,未减去。

see Ayush's comment below. It looks like the offset is intended to be added, not subtracted.

编辑#2:海报,自1970年以来的时间戳在墨尔本时间可能不需要。大多数应用程序可能永远不需要跟踪这样的时间戳,在任何其他时区GMT。当时间向用户显示时间时,转换为时区。

Edit #2: after chatting with the poster, the timestamp since 1970 in Melbourne time was probably not actually needed. Most applications will probably never need to keep track of such a time stamp, in any other time zone than GMT. Convert to time zones when it's time to display times to the user.

这篇关于使用特定时区将NSDate转换为Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆