WebDevDanno WebDevDanno - 5 months ago 23
PHP Question

Format unformatted time number to readable 24 hour time

My client has entered some start and end dates into our system and I want to be able to format it with PHP.

The values are

930
and
1530
. Processing the
1530
variable is fine but its the
930
that returns false.

Here is my script so far but no success. Error returns
bool(false)
because it can't get a readable time (I believe?)

$time = DateTime::createFromFormat('Hi', $var);
$format = "H:i";
$result = $time->format($format);

Answer

That's because your initial time format is ambiguous. Assuming that you have time without leading zeros all the time one can do something like this:

$var = '930';
$time = DateTime::createFromFormat('Hi', str_pad($var, 4, '0', STR_PAD_LEFT));
$format = "H:i";
$result = $time->format($format);