Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

time

mysql

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!

like image 768
SirOracle Avatar asked Aug 08 '12 22:08

SirOracle


People also ask

What time format does MySQL use?

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.

How can store time in variable in PHP?

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.

How can I get current date and time in MySQL and PHP?

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.


1 Answers

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.

like image 81
nickb Avatar answered Sep 30 '22 11:09

nickb