Trying to convert standard time variable from form input to TIME format acceptable for MySQL INSERT. I might be going about it all wrong and could use some help. I've read through the MySQL TIME functions and PHP TIME functions but haven't found a solution yet.
Here's what I've 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>";
?>
The result is changing the time to 11:08:00 (not sure where the 8 minutes is coming from):
time_input: 11:00 AM
strtotime: 1344438000
mysql_time: 11:08:00
Any help is much appreciated!
MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.
Create a Date With mktime() The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above). The PHP mktime() function returns the Unix timestamp for a date.
The CURRENT_TIMESTAMP function in the MySQL database returns the current date and time (i.e. the time for the machine running that instance of MySQL). It is given as a value in the 'YYYY-MM-DD hh:mm:ss' format.
DateTime
will do this for you:
$time_input = '11:00 AM';
$date = DateTime::createFromFormat( 'H:i A', $time_input);
$formatted = $date->format( 'H:i:s');
I typically avoid strtotime()
when possible as it can be somewhat unpredictable.
You can see it work in this demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With