Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Unix timestamp to hours

All,

I have a database field which actually computes the time spent from the time the quiz started to the current time. This was done at some point of time (recorded as current time) and now I have an Unixtimestamp value for it

i.e. Suppose the start time was 5/5/2011 1pm and the current time was populated at 5/5/2011 2pm. So the difference is calculated and stored as an Unix timestamp.

Now I don't know when this was actually done and now I have to revert back to hours spent taking the quiz. So here a Unix timestamp needs to be converted back to hours, in this case return 1 hour. Can anyone please help me understand how to do this?

like image 230
name_masked Avatar asked Dec 28 '22 21:12

name_masked


2 Answers

You have the seconds, so just do something like

SELECT secondsField / 3600 as 'hours' FROM tableName
like image 126
Riccardo Galli Avatar answered Dec 30 '22 11:12

Riccardo Galli


Here is an example of finding the difference between two timestamps in days.

//Get current timestamp.
$current_time = time();

//Convert user's create time to timestamp.
$create_time  = strtotime('2011-09-01 22:12:55');

echo "Current Date \t".date('Y-m-d H:i:s', $current_time)."\n";
echo "Create Date \t".date('Y-m-d H:i:s', $create_time)."\n";

echo "Current Time \t ".$current_time." \n";
echo "Create Time \t ".$create_time." \n";

$time_diff = $current_time - $create_time;
$day_diff = $time_diff / (3600 * 24);

echo "Difference \t ".($day_diff)."\n";
echo "Quote Index \t ".intval(floor($day_diff))."\n";
echo "Func Calc \t ".get_passed_days($create_time)."\n";

function get_passed_days($create_time)
{
    return intval(floor((time() - $create_time) / 86400));
}

To convert to hours, instead of 86400 put 3600 instead.

Hope this helps.

like image 24
Zorayr Avatar answered Dec 30 '22 09:12

Zorayr