DucCuong
DucCuong

Reputation: 648

Incorrect value of datetime PHP and MySQL

In my site, I have a bootstrap datepicker which allows user to pick date in format of MM/DD/YYYY (e.g: 05/12/2014). Then when this data is submitted, I used the following PHP code to convert it into Datetime type, then insert into start_date (DATETIME datatype) column in MySQL .

$start_date = date('Y-m-d', $_POST['start_date']);

the insert query in PHP does nothing with reformatting the date. It just simply insert into corresponding column.

However, instead of inserting '2014-05-12', the value inserted into database is '1970-01-01'. That's so weird to me. Can anybody tell me what's wrong here. Is this that I used incorrect PHP function or incorrect timezone setting or ...

Upvotes: 0

Views: 351

Answers (3)

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

try to use

$date = str_replace('/', '-', $_POST['start_date']);
$start_date = date('Y-m-d', strtotime($date));

For more :- Converting between illogically formatted dates (changing /slash/ to -dash- )

Upvotes: 1

manlikeangus
manlikeangus

Reputation: 421

Just do this:

$start_date = date('Y-m-d', strtotime($_POST['start_date']));

Upvotes: 2

Ryan Kempt
Ryan Kempt

Reputation: 4209

You could also use strtotime() on your $_POST.

$start_date = date('Y-m-d', strtotime('05/12/2014'));

Upvotes: 1

Related Questions