i'm trying to convert a duration raw text to actual timestamp, but the format doesn't has any leading zeros and without that DateTime won't work, i don't really know how to split the values from the string, also i could have hours or not depending on the string itself, so it could be like
1:59 or 1:30:49, here's my actual attempt
$time = "1:59";
$duration_not_raw = DateTime::createFromFormat('H:i:s', $time);
$time2 = "1:51:59";
$duration_not_raw2 = DateTime::createFromFormat('H:i:s', $time2);
But obviously it breaks my whole page, if i would be able to split the values i'd do like
if (value) < 10
{
"0"..value
}
My Answer:
"1:59";
// Split the string by colon
$timeArray = explode(":", $time);
// Check the length of the array to determine if hours are present
if (count($timeArray) == 2) {
$hours = 0;
$minutes = $timeArray[0];
$seconds = $timeArray[1];
} elseif (count($timeArray) == 3) {
$hours = $timeArray[0];
$minutes = $timeArray[1];
$seconds = $timeArray[2];
}
// Create a DateTime object with the values
$timestamp = new DateTime();
$timestamp->setTime($hours, $minutes, $seconds);
echo $timestamp->format('Y-m-d H:i:s');
Rate this post
5 of 5 based on 3092 votesComments