简体   繁体   中英

Calculating days hours and minutes php

Alright, so I send an integer to my mysql database that's in milliseconds. Now, I'm trying to make it so that it says: Time Played: 1 day 3 hours and 15 minutes. But I'm having a hard time doing it, I just am able to get the minutes days and hours, but it'd be the amount of hours total the amount of days total and the minutes total, not all in one. I have my code like this:

$time = $timeRow['time'];    
$seconds = floor($time / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$days = round($hours / 24);
$milliseconds = $time % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
echo'Time Played: '.$days.' days '.$hours.' hours '.$minutes.' minutes';

Could anyone help me fix this up?

<?php

$time = $timeRow['time'] / 1000;

$days = floor($time / (24*60*60));
$hours = floor(($time - ($days*24*60*60)) / (60*60));
$minutes = floor(($time - ($days*24*60*60)-($hours*60*60)) / 60);
$seconds = ($time - ($days*24*60*60) - ($hours*60*60) - ($minutes*60)) % 60;

echo'Time Played: '.$days.' days '.$hours.' hours '.$minutes.' minutes '.$seconds.' seconds';

Test: http://codepad.viper-7.com/WBQQet

You're generating each variable from the original number, which is why it's telling you it's 1 day, and 35 hours; instead of 1 day and 11 hours.

You need to start subtracting values:

$seconds = floor($time / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$days = round($hours / 24);

for ($i = 0; $i < $days; $i++) {
    $hours -= 24;
}

And a similar piece of code for hours, minutes, and seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM