add two or more time strings in php

前端 未结 3 1216
后悔当初
后悔当初 2020-12-22 02:31

I have an array with times (string) e.g \"2:23\", \"3:2:22\" etc.

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

I want to find the

3条回答
  •  一向
    一向 (楼主)
    2020-12-22 03:19

    There is no builtin way of doing this - all time functions operate on times, not on durations. In your case, you can explode() and add the parts separately. I would recommend writing a class. Simple example:

    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
    

提交回复
热议问题