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

前提是你 提交于 2020-01-23 01:43:13

问题


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

I tried this :

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

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.

What could be the issue here?


回答1:


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.




回答2:


time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];


来源:https://stackoverflow.com/questions/10909387/convert-an-nsdate-to-a-unix-timestamp-using-a-particular-time-zone

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