计算MySQL / PHP花费的时间(时差)

时间:2013-10-07 12:56:10

标签: php mysql

我正在为我的工作场所开发一个任务管理应用程序。 我希望能够计算完成任务所需的时间,直到完成任务。

现在,我的应用程序将记录创建任务的日期和时间(例如:2013-09-28和14:42)。然后,它还会记录任务标记为已完成的日期和时间。

我知道我可以使用MySQL DATEDIFF()计算它所用的天数,但我想知道如何计算其余的(小时和分钟)。

基本上我想要一个输出说: “此任务需要2天,4小时30分钟才能完成。”

有人建议我如何做到这一点吗?

提前感谢您的帮助。

祝你好运, 寺门

2 个答案:

答案 0 :(得分:1)

使用DateTime :(您希望更好地格式化结果)

    $q = new DateTime('2013-10-11 10:10:11');
    $w = new DateTime('2013-11-18 14:13:16');
    $result = $w->diff($q);
    $string = "This task took ";
    if ($result->y > 0) {$string .= $result->y.' years, ';}
    if ($result->m > 0) {$string .= $result->m.' months, ';}
    if ($result->d > 0) {$string .= $result->d.' days, ';}
    if ($result->h > 0) {$string .= $result->h.' hours, ';}
    if ($result->i > 0) {$string .= $result->i.' minutes, ';}
    if ($result->s > 0) {$string .= $result->s.' seconds ';}
    $string .= "to complete.";
    echo $string;

答案 1 :(得分:1)

使用示例:

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('2013-05-01 00:22:35', true);

输出:

4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

<强> Link to the function.