我有以下数组。
Array
(
[0] => 25:50
[1] => 21:00
[2] => 42:40
)
我正在尝试在 php 中添加小时数,我已经尝试了以下代码。但它让我错误的时间计算。
$time_cal = 0;
foreach ($time as $time_cal) {
$time_cal += strtotime($time_cal);
}
echo date('H:i', strtotime($time_cal));
这个strtotime函数背后的原因是只给出不到24小时的时间计算,这是正确的,但是当我尝试超过24小时(如25:55,44:44)时,给了我错误的计算。
任何想法 ?
这段代码可能对你很有帮助。 我创建了两个函数1) explode_time2) second_to_hhmm
function explode_time($time) { //explode time and convert into seconds
$time = explode(':', $time);
$time = $time[0] * 3600 + $time[1] * 60;
return $time;
}
function second_to_hhmm($time) { //convert seconds to hh:mm
$hour = floor($time / 3600);
$minute = strval(floor(($time % 3600) / 60));
if ($minute == 0) {
$minute = "00";
} else {
$minute = $minute;
}
$time = $hour . ":" . $minute;
return $time;
}
$time = 0;
$time_arr = array("23:59","01:01","2:50");
foreach ($time_arr as $time_val) {
$time +=explode_time($time_val); // this fucntion will convert all hh:mm to seconds
}
echo second_to_hhmm($time); // this function will convert all seconds to HH:MM.
你可以使用它。
$remove_mins = date('H', strtotime( $time_to_add));
$time_cal = 0;
foreach ($time as $time_cal) {
$time_cal = date('H:i', strtotime("+" . $remove_mins . " hour",strtotime( $time_cal)));
}
echo date('H:i', strtotime($time_cal));
当超过 24 小时时,如果您尝试添加分钟数,+hour 函数将不起作用,因此您只需要获取小时数而不需要分钟数
function AddTimeToStr($aElapsedTimes) {
$totalHours = 0;
$totalMinutes = 0;
foreach($aElapsedTimes as $time) {
$timeParts = explode(":", $time);
$h = $timeParts[0];
$m = $timeParts[1];
$totalHours += $h;
$totalMinutes += $m;
}
$additionalHours = floor($totalMinutes / 60);
$minutes = $totalMinutes % 60;
$hours = $totalHours + $additionalHours;
$strMinutes = strval($minutes);
if ($minutes < 10) {
$strMinutes = "0" . $minutes;
}
$strHours = strval($hours);
if ($hours < 10) {
$strHours = "0" . $hours;
}
return($strHours . ":" . $strMinutes);
}
// your sample
echo AddTimeToStr(array("25:50", "21:00", "42:40")) . "<br/>";
// more flexibility. Lets you specify more than 99 hours
echo AddTimeToStr(array("100:50", "00:05", "22:40")) . "<br/>";
// check before, at, after hour boundaries
echo AddTimeToStr(array("00:50", "00:09")) . "<br/>";
echo AddTimeToStr(array("00:50", "00:10")) . "<br/>";
echo AddTimeToStr(array("00:50", "00:11")) . "<br/>";
要获取小时数:
substr($time_cal,0,2);
要获取会议记录:
substr($time_cal,3,2);
然后转换为数字,因为它是一个字符串
您可以使用
DateTime
对象对日期进行操作
$dates = array("21:00", "01:05", "03:00");
$sum = new DateTime("00:00");
foreach($dates as $date)
{
$elements = explode(':',$date);
$hours = (string)((int)$elements[0]);
$minutes = (string)((int)$elements[1]);
$dv = new DateInterval('PT'.$hours.'H'.$minutes.'M');
$sum->add($dv);
}
echo $sum->format('H:i');
这将输出01:05
因为它会自动对小时进行取模。