在php中添加两个或更多个时间字符串 [英] add two or more time strings in php
本文介绍了在php中添加两个或更多个时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含时间(字符串)的数组,例如2:23,3:2:22等。
$ times = array(2:33,4:2:22,3:22)// loner
我想找到所有数组的总和。
有没有办法可以添加像2:33和3:33(i:s)
谢谢
解决方案>
没有内置的方式这样做 - 所有的时间功能都在运行,
不在持续时间。在您的情况下,您可以 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->分钟+ = $ d->分钟;
$ this->秒+ = $ d->秒;
while($ this->秒> = 60){
$ this->秒 - = 60;
$ this->分钟++;
}
while($ this->分钟> = 60){
$ this->分钟 - = 60;
$ this->小时++;
}
}
public function __toString(){
return implode(':',array($ this-> hours,$ this-> minutes ,$ this->秒));
}
}
$ d1 =持续时间:: fromString('2:22');
$ d1-> add(Duration :: fromString('3:33'));
echo $ d1; // should print 5:55
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 total sum of all array.
Is there a way that I could add times like "2:33" and "3:33" ("i:s")
thanks
解决方案
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
这篇关于在php中添加两个或更多个时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文