是否有一个PHP函数,返回日期和时间在相同的格式MySQL函数NOW()?

我知道如何使用date()来做到这一点,但我在问是否有一个函数仅用于此。

例如,返回:

2009-12-01 00:00:00

当前回答

你可能会发现这很有用

new \DateTime()

其他回答

我喜欢user1786647发布的解决方案,我对它进行了一些更新,将timezone更改为一个函数参数,并添加了可选的支持,可以传递Unix时间或datetime字符串来用于返回的日期戳。

它还为运行PHP 5.3以下版本的用户提供了"setTimestamp"的回退:

function DateStamp($strDateTime = null, $strTimeZone = "Europe/London") {
    $objTimeZone = new DateTimeZone($strTimeZone);

    $objDateTime = new DateTime();
    $objDateTime->setTimezone($objTimeZone);

    if (!empty($strDateTime)) {
        $fltUnixTime = (is_string($strDateTime)) ? strtotime($strDateTime) : $strDateTime;

        if (method_exists($objDateTime, "setTimestamp")) {
            $objDateTime->setTimestamp($fltUnixTime);
        }
        else {
            $arrDate = getdate($fltUnixTime);
            $objDateTime->setDate($arrDate['year'], $arrDate['mon'], $arrDate['mday']);
            $objDateTime->setTime($arrDate['hours'], $arrDate['minutes'], $arrDate['seconds']);
        }
    }
    return $objDateTime->format("Y-m-d H:i:s");
}

我的回答是多余的,但如果你是强迫症,视觉导向,你只需要在你的代码中看到now关键字,使用:

date( 'Y-m-d H:i:s', strtotime( 'now' ) );

我一直在寻找同样的答案,我已经提出了这个解决方案,适用于PHP 5.3或更高版本:

$dtz = new DateTimeZone("Europe/Madrid"); //Your timezone
$now = new DateTime(date("Y-m-d"), $dtz);
echo $now->format("Y-m-d H:i:s");
date('Y-m-d H:i:s')

更多详情请点击这里:http://pl.php.net/manual/en/function.date.php

你可以使用date函数:

date("Y-m-d H:i:s");