【问题标题】:Multiplication of a time in PHPPHP中时间的乘法
【发布时间】:2015-05-31 09:05:17
【问题描述】:

我需要在 PHP 中乘以时间

$maritime ='01:10:00';       

我需要将此 $maritime 增加到 5
我想得到这样的答案

01:10:00*5 =  05:50:00

【问题讨论】:

  • 你有没有尝试过实现目标?
  • 是的,我在 php 中添加了两个时间函数,但无法获得任何乘法函数
  • 您对01:10:00 的期望结果如何?
  • 这些时间取自mysql表中的时间格式
  • 如果您想使用日期间隔执行此操作,请在此处查看 stackoverflow.com/questions/11556731/… 以获取想法和代码

标签: php time


【解决方案1】:

这是你应该做的

第 1 步:将您的小时数转换为秒数

$seconds = strtotime("1970-01-01 $maritime UTC");

第二步:直接相乘

$multiply = $seconds * 5;

第 3 步:将秒转换回小时,您就完成了!

echo gmdate("d H:i:s",$multiply);

所以你的最终代码应该是

<?php
$maritime ='01:10:00';
$seconds = strtotime("1970-01-01 $maritime UTC");
$multiply = $seconds * 5;  #Here you can multiply with your dynamic value
echo gmdate("d H:i:s",$multiply);

这是显示输出的Link of Eval

更新:

如果你工作超过一天

即时间*25次,则多于一天

那么我的输出将是02 05:10:00

但如果你想在几个小时内严格你应该使用DateTime

<?php
$maritime ='01:10:00';
$seconds = strtotime("1970-01-01 $maritime UTC");
$multiply = $seconds * 25;  #Here you can multiply with your dynamic value
$seconds = $multiply;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
?>

这里是Eval Link

【讨论】:

  • 是的,这比我的解决方案更好。
  • @SulthanAllaudeen 用乘数 25 试试,但它不起作用
  • 同值01:10:00?
  • @SulthanAllaudeen 是的,请参阅:eval.in/373221
  • @Rizier123 这个值是不是02 05:10:00 的意思是25小时10分钟也就是29:10:00
【解决方案2】:

只需将时间转换为基本单位(在本例中为秒),然后将其相乘再转换回来。

这里是一个简单的示例,请注意toSeconds 中没有错误检查,您可能希望在fromSeconds 中处理 00。

function toSeconds($time){
  $arr = explode(":", $time);
  return $arr[0]*3600 + $arr[1]*60 + $arr[2];
}

function fromSeconds($seconds){
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes = floor($seconds/60);
  $seconds -= $minutes*60;
  return "$hours:$minutes:$seconds";
}

【讨论】:

    【解决方案3】:

    很简单。试试这个

    $your_time = "01:10:00";
    date_default_timezone_set ("UTC");
    $secs = strtotime($your_time ) - strtotime("00:00:00");
    echo date("H:i:s",$secs * 5);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多