Shawn Sonnier
Shawn Sonnier

Reputation: 533

How to convert a date and time to be stored in mysql datetime

How do I convert this to be stored in mysql database with a datetime field?

$phptime = '02/21/2014 9:30 am';

Upvotes: 1

Views: 333

Answers (5)

rc_luke
rc_luke

Reputation: 111

Convert the string to a timestamp, then use the php date function to get it in the format you want.

$datetimeString = date( 'Y-m-d H:i:s', strtotime( $phptime ) );

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

MySQL solution: Use STR_TO_DATE function with the php datetime value as input.

mysql> select str_to_date( '02/21/2014 9:30 am', '%m/%d/%Y %h:%i %p' ) dt;
+---------------------+
| dt                  |
+---------------------+
| 2014-02-21 09:30:00 |
+---------------------+
1 row in set (0.00 sec)

Refer to:

Upvotes: 1

Mike
Mike

Reputation: 16

Try using strtotime

So like this:

strtotime($phptime);

Upvotes: 0

Oath Comrade
Oath Comrade

Reputation: 293

I had the experience that you have to separate the components and rearrange them to the mysql datetime format. I have done this before posting it to php and slice it in jquery.

Upvotes: 0

John Conde
John Conde

Reputation: 219814

Use DateTime::createFromFormat() to read in and format the date.

$phptime = '02/21/2014 9:30 am';
$dt = DateTime::createFromFormat('m/d/Y g:i a', $phptime);
$mysqltime = $dt->format('Y-m-d H:i:s');

Upvotes: 3

Related Questions