【问题标题】:Add specific hours in a specific time in php [duplicate]在php中的特定时间添加特定时间[重复]
【发布时间】:2017-06-29 04:32:39
【问题描述】:

以下是有助于在当前时间添加特定时间的代码

date('H:i', strtotime('+1 hours'));

如果时间和时间是动态的,我应该如何添加时间。例如,我希望将 08:00 的时间增加 2 小时,但是这两件事都保存在变量中

$hours = "2";

$day_time = "08:00";

我尝试了以下方法,但没有成功

$new_time = date($day_time, strtotime('+$hours hours'));

谁能告诉我怎么做

【问题讨论】:

  • @Cyclonecode 尝试不起作用,收到错误“遇到格式不正确的数值”
  • 在进一步使用此代码之前,我建议您使用真正的时间戳而不是仅仅几个小时。人类擅长处理时间等抽象事物,但计算机却不行。在任何时候都使用某种类型的年月日期,这样您以后在代码中就会更容易。

标签: php datetime time


【解决方案1】:

试试这个

echo date("H:i", strtotime("+{$hours}hour ".$day_time));

【讨论】:

    【解决方案2】:

    试试这个

    $h = 2 ;
    $time="08:00";
    $time = date('H:i', strtotime($time.'+'.$h.' hour'));
    echo $time;
    

    【讨论】:

      【解决方案3】:

      试试下面的代码,

      <?php
          $hours = "2";
          $day_time = "08:00";
          $new_time = date('H:i',strtotime($day_time.'+ '.$hours.' hour'));
          echo $new_time;
      ?>
      

      输出:10:00

      【讨论】:

        【解决方案4】:

        使用日期时间会更好避免

        “遇到格式不正确的数值”

        $date = new DateTime($day_time);
        $date->modify("+".$hours." hours");
        echo $date->format("H:i");
        

        【讨论】:

          【解决方案5】:

          这样试试,

          $hours = 2;
          $day_time = "08:00";
          $new_time = date('H:i',strtotime($day_time."+$hours hours"));
          

          【讨论】:

            【解决方案6】:

            那是因为您在单引号内使用了变量。有一些方法可以解决这个问题:

            //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 的魅力和诅咒,你总是可以用不止一种方式做事。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-08-24
              • 1970-01-01
              • 2018-07-17
              • 1970-01-01
              • 2019-06-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多