PHP Function to Convert 12 Hour Time to 24 Hour Format


/ Published in: PHP

Convert 12-hour time format with hour, minutes, seconds, and meridiem into 24-hour format. Performs data correction to make sure hours, minutes and seconds have leading zeros if needed.

The trick here is to use strtotime() where we pass the time string in this format: "hh:mm:ss meridiem"
Example: "02:30:00 pm"


Copy this code and paste it in your HTML
  1. <?php
  2. function to_24_hour($hours,$minutes,$seconds,$meridiem){
  3. $hours = sprintf('%02d',(int) $hours);
  4. $minutes = sprintf('%02d',(int) $minutes);
  5. $seconds = sprintf('%02d',(int) $seconds);
  6. $meridiem = (strtolower($meridiem)=='am') ? 'am' : 'pm';
  7. return date('H:i:s', strtotime("{$hours}:{$minutes}:{$seconds} {$meridiem}"));
  8. }
  9.  
  10. echo to_24_hour( 1, 2, 3, 'pm' ); // Returns 13:02:03
  11. echo to_24_hour( '02', '30', '00', 'pm' ); // Returns 14:30:00
  12. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.