Try: date("Y-m-d H:i:s") which uses the numeric equivalents.quý khách hàng sẽ xem: Convert php date lớn mysql datetime format
edit: switched G to H, though it may not have sầu impact, you probably want to lớn use 24-hour format with leading 0s.
Bạn đang xem: Php — chuyển đổi chuỗi thành date và datetime
From the comments of php"s date() manual page:
You had the "Y" correct - that"s a full year, but "M" is a three character month, while "m" is a two digit month. Same issue with "D" instead of "d". "G" is a 1 or 2 digit hour, where "H" always has a leading 0 when needed.
Here"s an alternative sầu solution: if you have the date in PHPhường as a timestamp, bypass handling it with PHP. and let the DB take care of transforming it by using the FROM_UNIXTIME function.I use the following PHP code lớn create a variable that I insert inlớn a MySQL DATETIME column. I use this function (PHP. 7)
function getDateForDatabase(string $date): string $timestamp = strtotime($date); $date_formated = date("Y-m-d H:i:s", $timestamp); return $date_formated;Older versions of PHP (PHPhường function getDateForDatabase($date) $timestamp = strtotime($date); $date_formated = date("Y-m-d H:i:s", $timestamp); return $date_formated; Format MySquốc lộ datetime with PHP
$date = """.date("Y-m-d H:i:s", strtotime(str_replace("-", "/", $_POST)))."""; There is no need no use the date() method from PHP if you don"t use a timestamp. If dateposted is a datetime column, you can insert the current date like this:
$db->query("INSERT INTO table (dateposted) VALUES (now())"); A small addendum to lớn accepted answer: If database datetime is stored as UTC (what I always do), you should use gmdate("Y-m-d H:i:s") instead of date("Y-m-d H:i:s").
Or, if you prefer khổng lồ let MySquốc lộ handle everything, as some answers suggest, I would insert MySQL"s UTC_TIMESTAMP, with the same result.
Note: I understood the question referring to lớn current time.Using DateTime class in PHP7+:
$now = date("Y-m-dTH:i:s.uP", time());Notice the .uP.
More info: https://darkedeneurope.com/a/6153162/8662476Highly active sầu question. Earn 10 reputation in order lớn answer this question. The reputation requirement helps protect this question from spam and non-answer activity.
Not the answer you're looking for? Browse other questions tagged php mysql or ask your own question.