dateWithTimeIntervalSince1970 not returning correct date

我们两清 提交于 2019-11-30 05:24:33

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/20154361/datewithtimeintervalsince1970-not-returning-correct-date

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