Military time uses a 24-hour format ranging from 0000 (midnight) to 2359 (11:59 PM). To convert this into standard 12-hour time (AM/PM), we use PHP to format and manipulate the time string.
We'll assume the input is a 4-digit number, like 1530
(which means 3:30 PM).
We can use PHP's DateTime
class to handle the conversion cleanly:
<?php
$militaryTime = "1530";
// Convert to a DateTime object using 24-hour format
$date = DateTime::createFromFormat('Hi', $militaryTime);
// Format into standard 12-hour time with AM/PM
$standardTime = $date->format('g:i A');
echo "Standard Time: " . $standardTime;
?>
Standard Time: 3:30 PM
To avoid errors from invalid input like 2560
or 99ab
, add a validation step:
<?php
$militaryTime = "2560"; // example of invalid input
if (preg_match('/^([01]\d|2[0-3])[0-5]\d$/', $militaryTime)) {
$date = DateTime::createFromFormat('Hi', $militaryTime);
echo $date->format('g:i A');
} else {
echo "Invalid military time format.";
}
?>
/^([01]\d|2[0-3])[0-5]\d$/
ensures the input is a valid time between 0000 and 2359.
The DateTime
class handles all the complexity of time formatting, including things like daylight savings and time zones if needed. It's clean, reliable, and future-proof.
Now you know: How to take a military time input and convert it into readable, user-friendly standard time using PHP. Easy to implement, essential for apps, logs, or any time-sensitive systems.
Related pages: