Home » Php » php – How to change this 24 hours time format in 12 Hours

php – How to change this 24 hours time format in 12 Hours

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi i am facing a problem while editing the plugin. the default time format of this plugin is 24 hours but i want to convert it into 12 hours with AM/PM as well.
Here is the code that i have

<div class="col-xs-4 col-sm-4 col-md-4">
    <div class="form-group qc-input-container">
        <select name="quickcab_form_departure_time_hour" id="quickcab_form_departure_time_hour" class="booking-input quickcab-select-input form-control" required>
            <option disabled selected><?php echo esc_html__('Hour', 'quickcab'); ?></option>
<?php
for ( $i = 1; $i <= 12; $i++ ) {
?>
            <option value="<?php echo sprintf('%02d', $i); ?>"><?php
                      echo sprintf('%02d', $i);
                    ?></option>
<?php
}
?>
        </select>
    </div>
How to&Answers:

You can easily get the 12 hours time by using date() function. I’m giving an example for you.

// suppose your time is 19:24:15
$date = '19:24:15'; 
echo date('h:i:s a', strtotime($date));

The output will be

07:24:15 pm

You can get the output also by using DateTime

$date = new DateTime('19:24:15');
echo $date->format('h:i:s a') ;

h is used for 12 digit time
i stands for minutes
s seconds
a will return am or pm (use in uppercase for AM PM)

Answer:

To keep it really simple you could just add another loop to 12 to get a full 24 hours, then a simple change to the sprinf() will get you the AM and PM, like this

sprintf('%02dAM', $i);

and in the second loop

sprintf('%02dPM', $i)

So your code

<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group qc-input-container">
    <select name="quickcab_form_departure_time_hour" id="quickcab_form_departure_time_hour" class="booking-input quickcab-select-input form-control" required>
        <option disabled selected><?php echo esc_html__('Hour', 'quickcab'); ?></option>
<?php
// first 12 hours
for ( $i = 1; $i <= 12; $i++ ) {
?>
        <option value="<?php echo sprintf('%02dAM', $i); ?>"><?php echo sprintf('%02dAM', $i);?></option>
<?php
}
// second 12 hours
for ( $i = 1; $i <= 12; $i++ ) {
?>
        <option value="<?php echo sprintf('%02dPM', $i); ?>"><?php echo sprintf('%02dPM', $i);?></option>
<?php
}
?>

    </select>
</div>