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

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

例如,返回:

2009-12-01 00:00:00

当前回答

PHP的等效函数是time(): http://php.net/manual/en/function.time.php

其他回答

我喜欢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 now()函数,但可以使用date()来实现。

例子

function now() {
    return date('Y-m-d H:i:s');
}

如果需要更改时区,可以使用date_default_timezone_set()。

否则,您可以使用Carbon -一个简单的PHP API扩展DateTime。

使用PHP版本>= 5.4 DateTime可以做到这一点

echo (new \DateTime())->format('Y-m-d H:i:s');

看到它起作用了。

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

echo date("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");