Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: help me convert a timestamp to a formatted date/time

I'm really struggling to convert this timestamp to a nice formatted date string.

Here's the timestamp: "1316625985"

And here's the function I've made:

-(NSString*)timestamp2date:(NSString*)timestamp{
    NSString * timeStampString =timestamp;
    //[timeStampString stringByAppendingString:@"000"];   //convert to ms
    NSTimeInterval _interval=[timeStampString doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
    [_formatter setDateFormat:@"dd/MM/yy"];
    return [_formatter stringFromDate:date];
}

Trouble is, it keeps returning dates in 1972! (31/7/72) This is wrong, since it's a September 2011 date...

Can anyone suggest any solution?

Many thanks in advance,

like image 760
Eamorr Avatar asked Sep 21 '11 21:09

Eamorr


People also ask

Can you convert timestamp to date?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

How to convert timestamp to date py?

Import the “datetime” file to start timestamp conversion into a date. Create an object and initialize the value of the timestamp. Use the ” fromtimestamp ()” method to place either data or object. Print the date after conversion of the timestamp.

What is the format of a timestamp?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


2 Answers

Isn't epoch seconds since 1/1/1970? are you sure that you didn't leave the millisecond line in?

When I ran you're logic (without your line append 000 for ms), it worked. Here's what I did:

    NSString * timeStampString = @"1316641549";
    NSTimeInterval _interval=[timeStampString doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSLog(@"%@", date);

It outputted:

2011-09-21 17:46:14.384 Craplet[13218:707] 2011-09-21 21:45:49 +0000

like image 160
bryanmac Avatar answered Nov 15 '22 13:11

bryanmac


Just divide your [timeStampString doubleValue] by a thousand like:

NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStampString doubleValue]/1000.0];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:@"dd/MM/yy"];
return [_formatter stringFromDate:date];

or try [timeStampString longLongValue]/1000.0 instead

Good Luck!

like image 36
PedroJost Avatar answered Nov 15 '22 12:11

PedroJost