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

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

例如,返回:

2009-12-01 00:00:00

当前回答

没有内置的PHP now()函数,但可以使用date()来实现。

例子

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

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

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

其他回答

没有内置的PHP now()函数,但可以使用date()来实现。

例子

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

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

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

你可能会发现这很有用

new \DateTime()

你可以使用date函数:

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

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

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

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