Bhavesh
Bhavesh

Reputation: 4677

How to convert a date-time into string in PHP?

I have a date as follows.

$discount_start_date='03/27/2012 18:47';

$start_date=new DateTime($discount_start_date);
$start_date->format('Y/m/d H:i:s');

How can I convert it to a string in PHP so that it can be stored into MySql? I'm from Java background and very new to PHP.

Upvotes: 10

Views: 72966

Answers (2)

Yada
Yada

Reputation: 31225

Don't use DateTime. The normal php way of doing this sort of thing is to use date() and strtotime();

$discount_start_date = '03/27/2012 18:47';    
$start_date = date('Y-m-d H:i:s', strtotime($discount_start_date));

Upvotes: 15

Thomas Wright
Thomas Wright

Reputation: 1309

You don't actually need to convert it into a string. MySQL has a date, time, datetime, as well as timestamp native data types. You should be able to simply insert the date immediately without casting it to a string so long as you insert it into one of these fields and have it formatted properly.

Upvotes: 3

Related Questions