Home > Software engineering >  PHP String to timestamp without leading zero
PHP String to timestamp without leading zero

Time:05-26

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
}

CodePudding user response:

Use the appropriate format string ("G:i" for $time, "G:i:s" for $time2) instead of "H:i:s" for DateTime::createFromFormat() OR use date_create() and let just php figure it out:

$time = "1:59";    
$duration_not_raw = date_create($time);


$time2 = "1:51:59";
$duration_not_raw2 = date_create($time2);

See https://www.php.net/manual/en/datetime.formats.time.php for formats date_create() can understand and https://www.php.net/manual/en/datetime.createfromformat.php for format strings to use with DateTime::createFromFormat()

CodePudding user response:

I solved it with a different method, i'm sorry because i haven't been clear in the first time in what i needed.

$str_time = "1:59";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600   $minutes * 60   $seconds : $hours * 60   $minutes;
$time_milliseconds = $time_seconds * 1000
  • Related