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

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

例如,返回:

2009-12-01 00:00:00

当前回答

使用这个函数:

function getDatetimeNow() {
    $tz_object = new DateTimeZone('Brazil/East');
    //date_default_timezone_set('Brazil/East');

    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('Y\-m\-d\ h:i:s');
}

其他回答

我喜欢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");
}

我一直在寻找同样的答案,我已经提出了这个解决方案,适用于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");

你可以使用正确格式的PHP日期函数作为参数,

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

MySQL函数NOW()返回当前时间戳。我发现PHP的唯一方法是使用下面的代码。

$curr_timestamp = date('Y-m-d H:i:s');

你可能会发现这很有用

new \DateTime()