In PHP, how can I convert string time such as "84:12:49" (hours greater than 24) to DateTime object? I tried convert it to unix first but it doesn't return proper value
$time = explode(":", $time);
$timeUnix = mktime(intval($time[0]),intval($time[1]), intval($time[2]));
CodePudding user response:
You want to get a DateInterval object. You could be use ->diff() with two DateTime objects.
$time = '84:12:49';
[$hours, $minutes, $seconds] = explode(':', $time);
$totalSeconds = $seconds $minutes*60 $hours*3600;
$interval = (new DateTime())->diff(DateTime::createFromFormat('U', time() $totalSeconds));
var_dump($interval);
Output
object(DateInterval)#3 (16) {
["y"]=> int(0)
["m"]=> int(0)
["d"]=> int(3)
["h"]=> int(12)
["i"]=> int(12)
["s"]=> int(48)
["f"]=> float(0.996002)
["weekday"]=> int(0)
["weekday_behavior"]=> int(0)
["first_last_day_of"]=> int(0)
["invert"]=> int(0)
["days"]=> int(3)
["special_type"]=> int(0)
["special_amount"]=> int(0)
["have_weekday_relative"]=> int(0)
["have_special_relative"]=> int(0)
}
CodePudding user response:
Use DateInterval like so...
<?php
$time = '84:12:49';
$timeArray = explode(":", $time);
$date = new DateTime();
$date->add(new DateInterval('PT' . $timeArray[0] . 'H' . $timeArray[1] . 'M' . $timeArray[2] . 'S'));
// Your DateTime object is $date, display it like so for example...
echo $date->format('Y-m-d H:i:s');
We are creating a new DateTime object starting now.
We are then using DateInterval to add a new time period (PT) (starting from now) with the provided hours, minutes and seconds.
