Convert PHP variable "11:00 AM" to MySQL time format

Attempt to convert a standard time variable from form input to TIME format, acceptable for MySQL INSERT. Maybe I'm wrong and can use some help. I read the MySQL TIME functions and the PHP TIME functions, but have not yet found a solution.

Here is what I tried as an example:

<?php $time_input = '11:00 AM'; $strtotime = strtotime($time_input); $mysql_time = date('H:m:s',$strtotime); echo "<p>time_input: $time_input</p>"; echo "<p>strtotime: $strtotime</p>"; echo "<p>mysql_time: $mysql_time</p>"; ?> 

As a result, the time changes until 11:08:00 (I don’t know where 8 minutes come from):

 time_input: 11:00 AM strtotime: 1344438000 mysql_time: 11:08:00 

Any help is much appreciated!

+6
source share
2 answers

DateTime will do it for you:

 $time_input = '11:00 AM'; $date = DateTime::createFromFormat( 'H:i A', $time_input); $formatted = $date->format( 'H:i:s'); 

I usually avoid strtotime() , as this can be somewhat unpredictable.

You can see how it works in this demo .

+8
source

m is the month format with leading zeros (August, i.e. 08), you want i (minutes with leading zeros):

 $mysql_time = date('H:i:s',$strtotime); 

PHP date docs

+4
source

Source: https://habr.com/ru/post/922424/


All Articles