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

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


当前回答

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

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

其他回答

我使用这个函数(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;
}

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

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

注意。up。

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

IMO除了在前面的回答中提供的date()函数选项外,您还应该仔细考虑其使用的服务器时区设置,这可能与数据库设置不同。如果需要UTC时区,那么gmdate()函数(它具有与date()相同的选项)对于特定情况会更方便。

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

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

在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');
}