Convert an NSDate to a Unix timestamp using a particular time zone

喜欢而已 提交于 2019-12-04 12:13:15

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

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.

For that, you can use your NSTimeZone instance

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

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


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

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.

Dhruv
time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!