如何添加不同的时间戳

时间:2019-08-22 01:19:59

标签: php laravel laravel-5 php-carbon

例如,我在添加两(2)个时间戳时遇到问题:

00:30:00
00:45:31
========
01:15:31 

我不知道如何使用带有碳的laravel来做到这一点...

4 个答案:

答案 0 :(得分:3)

您不能像整数一样添加时间。一种方法是将其转换为另一种格式,然后添加它。添加它们后,将其转换回时间类型。

例如,尝试以下操作:

$time1 = "00:30:00";
$time2 = "00:45:31";

$secs = strtotime($time2) - strtotime("00:00:00");
$result = date("H:i:s", strtotime($time1) + $secs);

dd($result); // "01:15:31"

答案 1 :(得分:0)

我的做法是制作TimeHelper类,在其中声明与时间计算相关的所有静态方法。 所以基本上,我会在TimeHelper类中使像这样的静态函数:

public static function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
        $time2_arr = [];
        $time1 = $time1;
        $time2_arr = explode(":", $time2);
        //Hour
        if(isset($time2_arr[0]) && $time2_arr[0] != ""){
            $time1 = $time1." +".$time2_arr[0]." hours";
            $time1 = date("H:i:s", strtotime($time1));
        }
        //Minutes
        if(isset($time2_arr[1]) && $time2_arr[1] != ""){
            $time1 = $time1." +".$time2_arr[1]." minutes";
            $time1 = date("H:i:s", strtotime($time1));
        }
        //Seconds
        if(isset($time2_arr[2]) && $time2_arr[2] != ""){
            $time1 = $time1." +".$time2_arr[2]." seconds";
            $time1 = date("H:i:s", strtotime($time1));
        }

        return date("H:i:s", strtotime($time1));
    } 

因此,无论您需要求和两次,只要调用TimeHelper :: addTwoTimes(arg1,arg2);

我从以下主题的用户Cha中获得了示例功能:PHP add up two time variables

答案 2 :(得分:0)

这样可以实现在Carbon日期中添加两次。内嵌注释中显示了解释

$time1 = '00:30:00';
$time2 = '00:45:31';

// Use the first time to crate a new Carbon date
$baseDate = Carbon::parse($time1);

// Deconstruct the second time into hours, minutes and seconds
list($addHour, $addMinutes, $addSeconds) = explode(':', $time2);

// Add the hours, minutes and seconds to the Carbon object
$baseDate->addHours($addHour)->addMinutes($addMinutes)->addSeconds($addSeconds);

// Print the result: 00:30:00 + 00:45:31 = 01:15:31
echo "{$time1} + {$time2} = " .  $baseDate->toTimeString();

答案 3 :(得分:0)

您可以使用Carbon库中的CarbonInterval类:

$durations = [
    '00:30:00',
    '00:45:31',
];

function getDuration($string)
{
    [$hours, $minutes, $seconds] = explode(':', $string);

    return CarbonInterval::hours($hours)->minutes($minutes)->seconds($seconds);
}

$total = getDuration(array_shift($durations));

foreach ($durations as $duration) {
    $total->add(getDuration($duration));
}

echo $total->cascade()->format('%h:%i:%s'); // 1:15:31