Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert unix timestamp to human readable time?

I get a unix timestamp from the database and I am trying to create a human readable date from it. I am using this way

long t1=[time longLongValue];

NSDate* date=[NSDate dateWithTimeIntervalSince1970:t1];

where time is the timestamp. When I print date I get

1956-02-18 19:04:01 +0000 

instead of

2013-01-02 12:31:03 +0000

The timestamp was 1356765933449

like image 245
zzzzz Avatar asked Jan 02 '13 11:01

zzzzz


2 Answers

It is a matter of integer overflow, as Boris correctly pointed out in his answer.

I don't know what your time object is, but instead of a signed long int use a NSTimeInterval.

On iOS NSTimeInterval is currently defined as

typedef double NSTimeInterval;

but you shouldn't care too much about that. Sticking with type synonyms will protect you in case Apple decides to change the underlying definition to something else.

That said you should change your code to something like

NSTimeInterval epoch = [time doubleValue];
NSDate * date = [NSDate dateWithTimeIntervalSince1970:epoch];

Concerning the code maintainability issue I described before, here you are explicitly using a doubleValue (you don't have many options), but the good thing is that if Apple changes the NSTimeInterval definition to something not compatible with a double assignment, the compiler will let you know.

like image 162
Gabriele Petronella Avatar answered Oct 20 '22 22:10

Gabriele Petronella


Try this

- (NSString *) getDateFromUnixFormat:(NSString *)unixFormat
{

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[unixFormat intValue]];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy-h:mm"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    //NSDate *date = [dateFormatter dateFromString:publicationDate];
    NSString *dte=[dateFormatter stringFromDate:date];

    [dateFormatter release];
    return dte;

}
like image 29
Talha Avatar answered Oct 20 '22 22:10

Talha