gpt4 book ai didi

php - 考虑 PHP 中的日期计算持续时间

转载 作者:行者123 更新时间:2023-12-04 16:01:19 29 4
gpt4 key购买 nike

考虑到 PHP 中的日期戳,我如何计算持续时间?我在日期之间使用的日期格式是“Y-m-d H:i:s”,

我的工作代码只能计算时间之间的持续时间而不考虑日期。

下面是我的代码:

$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";

function hmsDiff ($assigned_time, $completed_time) {
$assigned_seconds = hmsToSeconds($assigned_time);
$completed_seconds = hmsToSeconds($completed_time);

$remaining_seconds = $assigned_seconds - $completed_seconds;

return secondsToHMS($remaining_seconds);
}
function hmsToSeconds ($hms) {
$total_seconds = 0;
list($hours, $minutes, $seconds) = explode(":", $hms);
$total_seconds += $hours * 60 * 60;
$total_seconds += $minutes * 60;
$total_seconds += $seconds;

return $total_seconds;
}

function secondsToHMS ($seconds) {
$minutes = (int)($seconds / 60);
$seconds = $seconds % 60;
$hours = (int)($minutes / 60);
$minutes = $minutes % 60;

return sprintf("%02d", abs($hours)) . ":" .
sprintf("%02d", abs($minutes)) . ":" .
sprintf("%02d", abs($seconds));

}

最佳答案

DateTime 有一个“diff”方法,它返回一个 Interval 对象。区间对象有一个方法"format" which allows you to customize the output .

#!/usr/bin/env php
<?php

$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";

$d1 = new DateTime($assigned_time);
$d2 = new DateTime($completed_time);
$interval = $d2->diff($d1);

echo $interval->format('%d days, %H hours, %I minutes, %S seconds');

注意:如果您没有使用 5.3.0+,这里有一个很好的答案:https://stackoverflow.com/a/676828/128346 .

关于php - 考虑 PHP 中的日期计算持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10712577/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com