NSDate dateWithTimeIntervalSince1970 NOT returning GMT/UTC time
I tried an experiment because I need to be able to generate a unix timestamp (since 1970) in the app I am working on.
NSLog(@"Getting timeIntervalSince1970");
double theLoggedInTokenTimestampDateEpochSeconds = [[NSDate date] timeIntervalSince1970];
This should've returned epoch seconds (since 1970) in GMT (Seconds since Jan 1, 1970). However, when conducting the experiment at at Mon Aug 15 09:54:30 2011, it returned 1313427270.504315
Testing this with a simple perl one-liner on my Mac OS Terminal, I get:
perl -e 'print scalar(localtime(1313427270))'
which returns Mon Aug 15 09:54:30 2011 ...
This is obviously not GMT time when I am in the SF Bay Area and my local timezone is set to "Cupertino". What is going on and how do I fix it please? I need to have my app send UTC time to the server when it communicates so wherever the user is time timestamp would be sent in one equal, valid time zone.
In another part of my app, when the user requests data from the server, it gets it sent in UTC -- converting it to be displayed as follows:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setTimeZone:nil];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSDate *conversationDate = [NSDate dateWithTimeIntervalSince1970:[theConversationTimeStampString intValue]];
NSString *conversationDateString = [dateFormatter stringFromDate:conversationDate];
[dateForma开发者_StackOverflow社区tter release];
and this works beautifully -- displaying the corrected time in the user's timezone and locale... so I know it is being done for incoming timestamps. So, what am I doing wrong with the first function (timeIntervalSince190) that stops it from being in GMT?
Thx
I don't think the first function is actually wrong, although it may look like it on the surface. The time interval you are receiving from timeIntervalSince1970 is NOT returning the time interval in GMT. Rather, it is returning the time interval between now and January 1, 1970 00:00:00 GMT. That might seem like a nitpick, but it is important: The interval values are nothing more than a scalar number of seconds since a fixed point in time. The interval itself is not in GMT, only its fixed reference point is.
I don't know perl, but I did a quick search for documentation on local time and it appears to take any time and print convert a standard date type into local time. That means that your time interval describing a fixed point in time is converted back into your local time at that point. When you display it from your command line, you are getting the local time again. So seeing that absolute time translated to your local time is what I would expect to see.
Depending on how exactly your service expects to receive UTC time, your time interval value is likely to be working just fine. Do you have evidence that it is not based on something other than your terminal check?
精彩评论