Search code examples
phptimestrtotimereformatting

Drop the :00 from the time when it's not necessary


What I currently have is a time range that is pulled from a database record in 23:54 (24 hour) format. My script below currently formats the time range as: 6:30am - 1:00pm but what I'd like it to do is drop the :00 for any "on the hour" times so it looks like: 6:30am - 1pm.

I know it probably sounds insignificant, but being able to format all times like that so things look tidier when it gets to 1pm - 6pm is the end goal. :-)

<?php
$daystarttime = date("g:ia", strtotime($record['daystarttime']));
echo $daystarttime;
$dayendtime = date("g:ia", strtotime($record['dayendtime']));

if (!$dayendtime == null) {
    echo " - ";
    echo $dayendtime;
}
?>

You're help is greatly appreciated. :-)


Solution

  • Use str_replace. If there is no ':00' in times, nothing will be replaced.

    $daystarttime = str_replace(':00', '', date("g:ia", strtotime($record['daystarttime'])));
    $dayendtime = str_replace(':00', '', date("g:ia", strtotime($record['dayendtime'])));