Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to convert from seconds to date

Tags:

php

Okay so I have an array of results from a table, we have a start and end time we are retrieving. the start/end time would look something like this:

1345497551   

Now I'm trying to convert this to a real time, for instance 1345497551 might become 2012/05/09 17:23:12 or something. I've found a few things but none seem to work correctly. one solution I tried, according to what someone was saying on another question on here, was

$createdate = date('H:i:s',$numberofsecs);  

where $numberofsecs was the time pulled in from the array. but this only ever outputs 17:00:00 repeatedly for every time we had available for testing.

How can I go about making this work correctly?

like image 394
Kynian Avatar asked Sep 05 '12 23:09

Kynian


People also ask

How do you convert seconds into data?

To convert a date to seconds:Get a timestamp in milliseconds using the geTime() method. Convert the result to seconds by dividing by 1000 .

How do I turn a timestamp into a 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 do you convert milliseconds to dates?

To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

How do you convert seconds?

To convert seconds to minutes, divide the number of seconds by 60, since there are 60 seconds in a minute. If you get a decimal in your answer, multiply only the decimal part by 60.


2 Answers

Assuming that that's a standard unix timestamp string (seconds since midnight 1/1/1970), then you should be able to use date as you mentioned, but just modify the format string:

echo date('Y/m/d H:i:s', $numberofsecs);

The example you mention where you were always getting 17:00:00 could have been because your test cases were all only datestamps, encoded as timestamps, and having an offset from GMT . . .

like image 79
ernie Avatar answered Oct 06 '22 08:10

ernie


I have tried below code:

$ts = 1345497551;
$date = new DateTime("@$ts");
echo $date->format('U = Y-m-d H:i:s');

output : 1345497551 = 2012-08-20 21:19:11

like image 43
Pragnesh Chauhan Avatar answered Oct 06 '22 07:10

Pragnesh Chauhan