user715564 user715564 - 1 year ago 110
MySQL Question

Convert string to mysql datetime with AM/PM

I am working on a WordPress plugin that allows the user to select a time using a jQuery dropdown script. The time is a string in the format of "5 : 34 PM". I need to save that value to my mysql database in the datetime format.

So far, I can save the date and time but the AM/PM is not being factored in.

Here is my PHP function:

function db_tables_insert() {
global $wpdb;
$table_name = $wpdb->prefix . 'tweettweet';
$tweet = $_POST["tweet"];
$time = $_POST["timepicker"];
$time=preg_replace('/\s+/', '', $time);
$date = "2015-02-08:";
$datetime = $date.$time;

'time' => $datetime,
'text' => $tweet,

In this example, the value saved to the database would be "2015-02-08 12:13:00" (assuming the user selected 12:13 for the time). The problem is, that value is the same whether the user selects 12:13 am or 12:13 pm.

I need a way to convert the string so that the "am/pm" is taken into consideration when saved to the database.

Answer Source

strtotime should be able to handle this.

echo date('Y-m-d H:i:s',strtotime('2014-12-12 12:34 AM'));

returns 2014-12-12 00:34:00