将整数转换为时间格式,以便您可以计算时间差

时间:2017-12-19 09:56:00

标签: php mysql

从我的用户表中我检索一个整数(例如60),该整数应该是用户可以用于其总休息时间的最大分钟数。

当用户进入和退出休息时,它会被重新安排在另一个表中:

    $timestamp = date("Y-m-d H:i:s");
    $sql = "INSERT INTO user_log (username, in_pause, action_time)
    VALUES ('$username', 1, '$timestamp')";

我输入时为1,输入时写为0 我计算用户的休息时间从这两个记录的时间戳持续多长时间(在我的SQL查询之后我将时间戳记放入$ zeiten []):

    $pause_start = new DateTime($zeiten[1]);
    $pause_ende = new DateTime($zeiten[0]);
    $pause_diff = $pause_start->diff($pause_ende);

到目前为止,此工作正常。但我似乎无法找到一种方法来操纵我的用户表中的整数(此处为60),以便我可以从中减去$ pause_diff。我希望能够计算用户离开的休息时间 谢谢!

1 个答案:

答案 0 :(得分:0)

试试这段代码:

<?php

$max_minutes = (int) 60;
$zeiten[1] = '2000-01-01 10:00:00';
$zeiten[0] = '2000-01-01 10:10:00';

$pause_start = new DateTime($zeiten[1]);
$pause_ende = new DateTime($zeiten[0]);
$pause_diff = $pause_start->diff($pause_ende);
//$pause_diff->format('Y-m-d H:i:s');
$pause_diff_minutes =  $pause_diff->format('%i');

//var_dump((int) $pause_diff_minutes);

echo 'the differnece is: ' . ($max_minutes - (int) $pause_diff_minutes) . ' minutes';

结果是:

the differnece is: 50 minutes

You can play with the code here

更新了代码,显示了如何从60分钟中减去秒数:

<?php

$max_minutes = (int) 60;
$max_minutes_seconds = $max_minutes * 60; // max_minutes to seconds

$zeiten[1] = '2000-01-01 10:00:00';
$zeiten[0] = '2000-01-01 10:10:05';

$pause_start = new DateTime($zeiten[1]);
$pause_ende = new DateTime($zeiten[0]);
$pause_diff = $pause_start->diff($pause_ende);

$pause_diff_minutes =  $pause_diff->format('%i');
$pause_diff_seconds =  $pause_diff->format('%s');

// sum total diff in seconds
$total_pause_seconds = ((int) $pause_diff_minutes * 60) + $pause_diff_seconds;

$total_diff_seconds = ($max_minutes_seconds - $total_pause_seconds);

echo 'the differnece is: ' . $total_diff_seconds . ' seconds' . "\n";
echo 'which is: ' . floor($total_diff_seconds / 60) . ' minutes and ' . $total_diff_seconds % 60 .  ' seconds';

结果是:

the differnece is: 2995 seconds
which is: 49 minutes and 55 seconds

play with it here