PHP中的NOW()函数

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

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

例如,返回:

2009-12-01 00:00:00

#1楼

使用此功能:

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

#2楼

使用PHP版本> = 5.4 DateTime可以做到:

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

看到它工作 。


#3楼

我喜欢user1786647发布的解决方案,并对其进行了一些更新,以将时区更改为函数参数,并添加了对传递Unix time或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");
}

#4楼

使用strftime :

strftime("%F %T");
  • %F与%Y-%m-%d 。

  • %T与%H:%M:%S 。

这是有关ideone 的演示 。


#5楼

除了:

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

评论

暂无评论