Jachym
Jachym

Reputation: 485

Datetime format PHP and MySQL

I have the following problem. I have a string, which contains time and date as follows: dd/MM/yy hh:mm:ss This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".

Could you please help me with converting this string and then inserting it properly into MySQL? For the MySQL I use the standard INSERT INTO command.

Upvotes: 5

Views: 10843

Answers (4)

Amal
Amal

Reputation: 76646

From the DATETIME documentation:

MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.

I'd use PHP's DateTime class and DateTime::createFromFormat() method, and convert the data into a MySQL-compatible date string, like so:

$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');

Upvotes: 7

Anshad Vattapoyil
Anshad Vattapoyil

Reputation: 23483

Write a function to convert date,

function sqldate($date)
{
   $sql_date = date('Y-m-d H:i:s',strtotime($date));
   return $sql_date;
}

And your query look like,

$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";

Upvotes: 2

CIRCLE
CIRCLE

Reputation: 4879

Try this:

$parsedDate = date('Y-m-d H:i:s', strtotime($yourDate));
// Insert $parsedDate into your table column Date

Upvotes: 0

John Woo
John Woo

Reputation: 263883

You can convert it using STR_TO_DATE() along with your INSERT statement, eg.

INSERT INTO tableName (dateColumn)
VALUES(STR_TO_DATE('dd/MM/yy hh:mm:ss','%d/%m/%y %H:%i:%s'))

Upvotes: 0

Related Questions