简体   繁体   中英

How to add hours and minutes to a time in string form?

How can we add time interval to a time in string form.

$time = '10 : 00 : AM'; //initial time
$interval = '01 : 30'; //interval to be added

$newtime = $time + $interval;//how to do this

echo $newtime; //required: 11 : 30 : AM

The odd layouts of the text times make this a little fiddly but this will work

<?php
$in = '10 : 00 : AM';
$interval = '01 : 30';

$dt = DateTime::createFromFormat('H : i : A', $in);

$interval = str_replace([' ',':'],['','H'], $interval);
$interval = 'PT'. $interval . 'M';

$dt->add(new DateInterval($interval));

echo $dt->format('H:i:s') . PHP_EOL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM