什么是正确的格式传递给日期()函数在PHP中,如果我想将结果插入到一个MySQL datetime类型列?

我一直在尝试date('Y-M-D G: I:s'),但每次都只是插入“0000-00-00 00:00:00”。


当前回答

在PHP7+中使用DateTime类:

function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
 $dt = new DateTime();
 $dt->setDate($year, $month, $day);
 $dt->setTime(0, 0, 0, 0); // set time to midnight

 return $dt->format('Y-m-d H:i:s');
}

其他回答

这是一种更准确的方法。它把小数放在秒的后面,以提高精度。

$now = date('Y-m-d\TH:i:s.uP', time());

注意。up。

更多信息:https://stackoverflow.com/a/6153162/8662476

在PHP7+中使用DateTime类:

function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
 $dt = new DateTime();
 $dt->setDate($year, $month, $day);
 $dt->setTime(0, 0, 0, 0); // set time to midnight

 return $dt->format('Y-m-d H:i:s');
}

如果不使用时间戳,就没有必要使用PHP中的date()方法。如果dateposting是一个datetime列,你可以像这样插入当前日期:

$db->query("INSERT INTO table (dateposted) VALUES (now())");

问题是,你正在使用'M'和'D',这是一个文本表示,MySQL期望一个数字表示的格式2010-02-06 19:30:13

试试:date('Y-m-d H:i:s'),它使用了数字等量。

edit:将G切换为H,虽然它可能没有影响,但你可能想使用24小时格式,前导0。

我使用这个函数(PHP 7)

function getDateForDatabase(string $date): string {
    $timestamp = strtotime($date);
    $date_formated = date('Y-m-d H:i:s', $timestamp);
    return $date_formated;
}

PHP的旧版本(PHP < 7)

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