PHP Convert from strtotime into time

我们两清 提交于 2019-12-11 11:03:22

问题


I need to add multiple time values as in Hours:mins, so I use

strtotime($value1) + strtotime($value2)

to add all of them, how do I put them back as hours:mins ?

cant use

date("h:i")

it only works if hours < 24.

I appreciate your help. Thanks


回答1:


The function strtotime() returns the time in seconds since January 1 1970 00:00:00 UTC. So adding the return value of this function might not do what you would expect.

Instead of using the date functions we can manipulate the string and perform some basic arithmetic operations:

<?php
$value1 = "12:44";
$value2 = "13:47";

$arr1 = explode(':', $value1);
$arr2 = explode(':', $value2);

$totalMinutes = (int)$arr1[0] * 60 + (int)$arr1[1] + (int)$arr2[0] * 60 + (int)$arr2[1];

$hours = (int) ($totalMinutes / 60);
$minutes = $totalMinutes % 60; // Modulus: remainder when dividing with 60

echo $hours . ':' . $minutes;
?>



回答2:


Here is an function that will sum all your time values in format HH:MM:

function sum_time() {
    $i = 0;
    foreach (func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }
    if ($h = floor($i / 60)) {
        $i %= 60;
    }
    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06

demo




回答3:


Try this :

function time_convert($s) { 
    $m = 0; $hr = 0; $td = "now";
    if ($s > 59) { 
        $m = (int)($s/60); 
        $s = $s-($m*60); // sec left over 
        $td = "$m min"; 
    } 
    if ($m > 59) { 
        $hr = (int)($m / 60); 
        $m = $m - ($hr*60); // min left over 
        $td = "$hr hr"; 
        if ($hr > 1) {
            $td .= "s";
        }
        if ($m > 0) {
            $td .= ", $m min";
        }
    } 

    return $td; 
} 

And use it:

$time = (int) strtotime($v1) + strtotime($v2);
echo time_convert($time);

May it helps




回答4:


Another way with DateTime

$dt1 = new DateTime($value1);
$dt2 = new DateTime($value2);
$interval = $dt1->diff($dt2);
echo $interval->format('%a day(s) %h hour(s) %i minute(s)') . '<br />';
echo ($interval->format('%a') * 24 + $interval->format('%h')) . ' hour(s) ';
echo $interval->format('%i minute(s)');


来源:https://stackoverflow.com/questions/21560338/php-convert-from-strtotime-into-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!