在php中添加两个或多个时间字符串

时间:2009-09-02 21:51:10

标签: php datetime date time

我有一个带有时间(字符串)的数组,例如“2:23”,“3:2:22”等。

$times = array("2:33", "4:2:22", "3:22") //loner

我想找到所有数组的总和。

有没有办法可以添加“2:33”和“3:33”(“i:s”)等时间

感谢

3 个答案:

答案 0 :(得分:5)

您可能希望查看the PHP date/time functions - 一个选项是使用类似strtotime()的内容:

$midnight = strtotime("0:00");

// ssm = seconds since midnight
$ssm1 = strtotime("2:33") - $midnight;
$ssm2 = strtotime("3:33") - $midnight;

// This gives you the total seconds since midnight resulting from the sum of the two
$totalseconds = $ssm1 + $ssm2; // will be 21960 (6 hours and 6 minutes worth of seconds)

// If you want an output in a time format again, this will format the output in
// 24-hour time:
$formattedTime = date("G:i", $midnight + totalseconds);

// $formattedTime winds up as "6:06"

答案 1 :(得分:2)

没有内置的方法 - 所有时间功能都按时运行, 不是持续时间。在您的情况下,您可以explode()并添加部分 分别。我建议写一堂课。简单的例子:

class Duration {

    public static function fromString($string) {
        $parts = explode(':', $string);
        $object = new self();
        if (count($parts) === 2) {
            $object->minutes = $parts[0];
            $object->seconds = $parts[1];
        } elseif (count($parts) === 3) {
            $object->hours = $parts[0];
            $object->minutes = $parts[1];
            $object->seconds = $parts[2];
        } else {
            // handle error
        }
        return $object;
    }

    private $hours;
    private $minutes;
    private $seconds;

    public function getHours() {
        return $this->hours;
    }

    public function getMinutes() {
        return $this->minutes;
    }

    public function getSeconds() {
        return $this->seconds;
    }

    public function add(Duration $d) {
        $this->hours += $d->hours;
        $this->minutes += $d->minutes;
        $this->seconds += $d->seconds;
        while ($this->seconds >= 60) {
            $this->seconds -= 60;
            $this->minutes++;
        }
        while ($this->minutes >= 60) {
            $this->minutes -= 60;
            $this->hours++;
        }
    }

    public function __toString() {
        return implode(':', array($this->hours, $this->minutes, $this->seconds));
    }

}

$d1 = Duration::fromString('2:22');
$d1->add(Duration::fromString('3:33'));
echo $d1; // should print 5:55

答案 2 :(得分:0)

所以你想为一个时间添加一个持续时间,这意味着在一段时间内增加一些小时,分钟和秒钟?

也许你可以使用Dav的strtotime来获取从午夜开始的秒数,然后使用sscanf添加持续时间,因此:

$midnight = strtotime("0:00");

// ssm = seconds since midnight
$ssm1 = strtotime("2:33") - $midnight;

// sscanf the time string... you might need to include the possibility of seconds
list($hour, $minute) = sscanf("3:33", "%d:%d");

// a
$answer_ssm = $ssm + $hour * 3600 + $minute * 60;

echo strftime("%H:%M:%S", $answer_ssm);

无法从我所在的地方测试这个,请原谅任何语法错误...只是想举个例子。当然,你还需要遍历你的数组。