1

Hy ! I have 3 variables in database login_time, logout_time, total_time. The datatype of total_time is 'time' while the other two have 'date_time' datatype. What i did, I extract only login_time and logout_time in query and saved them into variables. I have login and logout time stored in variables. Now i need to calculate total time in Hours, min, second. I tried to calculate but it does not give exact time like this.

login_time = 2016-03-21 14:09:28

logout_time = 2016-03-21 14:10:22

total_time = 11:50:32

That's wrong ! What's my mistake ?

I tried many solutions but they did not resolved my problem ! Help me

 if(isset($_SESSION['start_time']))
{
    $start = $_SESSION['start_time'];
    $final = $_SESSION['final_time'];
    $diff = strtotime($final) - strtotime($start);

     //"%H:%M:%S"
    $total = date('H:i:s', $diff);
    $sql4 = "UPDATE log SET total_time = '$total' WHERE username = '$user'";
  $res4 = mysqli_query($link, $sql4);

2 Answers2

6

Try using DateTime.diff method like:

$start = new DateTime('2016-03-21 14:09:28');
$final = new DateTime('2016-03-21 14:10:22');
$diff = $final->diff($start);

var_dump($diff->format('%H:%I:%S'));

The result would be:

string(8) "00:00:54"
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

You could try this?

$difference = round(abs($to_time - $from_time) / 60,2). " minute";
$query = "UPDATE log SET total_time = '$difference' WHERE username = '$user'";
if($link->query($query)):
    echo 'Success';
endif;

Taken from here.

Note, this code looks like there is an SQLi injection present, ensure you're stripping the $user variable of HTML before inserting it into the database if it came from an un-trusted user input source.

Community
  • 1
  • 1
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • Have you converted it to a Data Type DateTime? Try that, hope it helps. Or use: `strtotime($to_time)` and the same to the `$from_time` – Jaquarh Mar 21 '16 at 09:36