PHP函数将12小时时间转换为24小时格式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP函数将12小时时间转换为24小时格式相关的知识,希望对你有一定的参考价值。

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"
  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. ?>

以上是关于PHP函数将12小时时间转换为24小时格式的主要内容,如果未能解决你的问题,请参考以下文章