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,
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.
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.
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.
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With