问题
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