【问题标题】:Adding time durations together with PHP与 PHP 一起添加持续时间
【发布时间】:2015-05-27 07:36:49
【问题描述】:

我有一个表格可以让人们输入不同的时间长度,例如:

input.time1 = "19:00"
input.time2 = "2:30"
input.time3 = "0:30"

我需要将这 3 次相加,然后从我拥有的基值 (21:00) 中减去它。

$base = "21:00"

那么我需要这样的东西:

$total = $time1 + $time2 + $time3; //equals 22:00
$base  = "21:00"; // set value
$diff  = $base - $total; // 21:00 - 22:00 = -1:00(mm:ss)

希望这一切都有意义,如果我需要更详细地解释任何事情,请告诉我。谢谢!

【问题讨论】:

  • 展示你目前所写的代码并解释为什么它没有达到你想要的效果。
  • 为此使用 DateInterval 类。
  • 那么你需要从添加的时间开始计算另一个时间吗?
  • 编写一个简单的小函数,可以将2:30 转换为150(分钟/秒)然后再返回,然后通过添加这些值来工作。
  • @Phylogenesis 我也会将DateTime::diff 添加到该工具箱中。

标签: php datetime time difference


【解决方案1】:

添加3次你应该这样做

<?php
$time = "19:00";
$time2 = "2:30";
$time3 = "0:30";
$secs = strtotime($time2)-strtotime("00:00");
$secs1 = strtotime($time3)-strtotime("00:00");
$result = date("H:i",strtotime($time)+$secs+$secs1);
echo $result;

现在$result 将具有附加值,

从增加的值中减去另一个值

$base  = "21:00";
$TimeStart = strtotime($result);
$TimeEnd = strtotime($base);
$Difference = ($TimeEnd - $TimeStart);
echo gmdate("H:i", $Difference);

【讨论】:

  • 不要使用时间戳函数来处理间隔。至少你可以在夏令时遇到有趣的小错误。
  • @deceze 好的,谢谢,我可以知道如何检查吗?
【解决方案2】:

$base = strtotime('21:00');
$total = strtotime($time1)+strtotime($time2);+strtotime($time3)
$diff = date("H:i", strtotime("$total - $base"));

希望这会有所帮助...

【讨论】:

    【解决方案3】:

    快速而肮脏的示例DIY方法:

    function string_to_int($time) {
        list($minutes, $seconds) = explode(':', $time);
        return $minutes * 60 + $seconds;
    }
    
    function int_to_string($seconds) {
        return sprintf('%d:%02d', floor($seconds / 60), $seconds % 60);
    }
    
    $duration = string_to_int('19:00') + string_to_int('2:30') + string_to_int('0:30');
    echo int_to_string($duration);
    

    您将xx:yy 转换为整秒的整数,将它们相加,然后将其格式化回xx:yy 以供人类可读的输出。

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2020-09-24
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多