dateWithTimeIntervalSince1970 not returning correc

2019-02-14 05:48发布

I have the following method below that is meant to retrieve and convert a unixTimeStamp from an API call to a NSDate object that I can easily manipulate and use. For some reason, this returns wrong values. An example would be when the unixTimeStamp is 1385152832, the date SHOULD be

Fri, 22 Nov 2013 20:40:31 GMT November 22, 2013 at 3:40:31 PM EST

but instead spits out: 45852-09-07 08:13:52 EST. Does anyone know why this would happen?

-(NSDate *)messageDate
{
    NSTimeInterval unixTimeStamp = [[self messageDateString] doubleValue];
    NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:unixTimeStamp];
    NSAssert(messageDate, @"messageDate should not be nil");
    return messageDate;
}

enter image description here

1条回答
叛逆
2楼-- · 2019-02-14 05:57

The messageDateString method is returning milliseconds since the epoch, not seconds since the epoch. Look at the value of unixTimeStamp in your debugger pane. It's 1384803782032. That is about 1000 times too large to be a current Unix timestamp.

An NSTimeInterval is measured in seconds, not milliseconds. Try this instead:

-(NSDate *)messageDate {
    NSTimeInterval unixTimeStamp = [[self messageDateString] doubleValue] / 1000.0;
    NSDate *messageDate = [NSDate dateWithTimeIntervalSince1970:unixTimeStamp];
    NSAssert(messageDate, @"messageDate should not be nil");
    return messageDate;
}
查看更多
登录 后发表回答