以下代码有助于在当前时间添加特定小时数
date('H:i', strtotime('+1 hours'));
如果时间和时间是动态的,我应该如何添加小时数。例如,我希望在08:00添加2小时,但这两件事都保存在变量中
$ hours =“2”;
$ day_time =“08:00”;
我尝试了以下但没有工作
$new_time = date($day_time, strtotime('+$hours hours'));
任何人都可以告诉我们如何做到这一点
答案 0 :(得分:0)
试试这个
$h = 2 ;
$time="08:00";
$time = date('H:i', strtotime($time.'+'.$h.' hour'));
echo $time;
答案 1 :(得分:0)
试试这个,
$hours = 2;
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time."+$hours hours"));
答案 2 :(得分:0)
试试这个
echo date("H:i", strtotime("+{$hours}hour ".$day_time));
答案 3 :(得分:0)
尝试以下代码,
<?php
$hours = "2";
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time.'+ '.$hours.' hour'));
echo $new_time;
?>
输出:10:00
答案 4 :(得分:0)
使用datetime会更好地避免
“遇到非正确形成的数值”
$date = new DateTime($day_time);
$date->modify("+".$hours." hours");
echo $date->format("H:i");
答案 5 :(得分:0)
那是因为你在单引号内使用变量。有一些方法可以解决这个问题:
//awful and you should avoid it
//(hard to read, unsafe use of direct variables inside strings):
$new_time = date($day_time, strtotime("+$hours hours"));
或
//still awful and you should avoid it too:
$new_time = date($day_time, strtotime('+{$hours} hours'));
或
//a little better, but still unsafe:
$new_time = date($day_time, strtotime('+' . $hours . ' hours'));
或
//better, safe because it only adds numeric values to the hours:
$new_time = date($day_time, strtotime(sprintf('+%d hours', $hours)));
或
//the ideal solution, safer to use and more professional:
$dateObj = new DateTime();
$dateObj->modify(sprintf('+%d hours', $hours));
$new_time = $dateObj->format("H:i");
这就是PHP的美丽和诅咒,你总能以多种方式做事。