[英]How to sum hours with existing datetime in PHP?
我有兩個存儲數據的字段,例如2018-03-26 11:20:35
和02:25:10
(2小時25分鍾10秒),第一個數據是日期和時間。 第二個只是時間。 我想總結一下,最后我的結果應該是2018-03-26 13:45:45
如何在php代碼中做到這一點?
我已經嘗試過這種方式:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
輸出:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
這是一個簡單的解決方案,跳過了一些檢查:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
您可以通過比較今天的"00:00:00"
和今天的$hours
來創建持續時間(以秒為單位)。 實際上, strtotime($hours)
返回今天的時間戳為$hours
,因此,兩個時間戳的相加不會得出預期的結果。
如果$hours
少於24小時,則可以使用:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
輸出:
2018-03-26 13:45:45
您可以執行以下操作:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
我假設您只需要幾個小時,而不是幾分鍾和幾秒鍾
編輯:
您可以使用regexp來做到這一點
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');
您應該檢查DateTime::add
:
例:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.