NOW() function in PHP

前端 未结 20 1714
遥遥无期
遥遥无期 2020-11-28 17:26

Is there a PHP function that returns the date and time in the same format as the MySQL function NOW()?

I know how to do it using date(), b

20条回答
  •  醉话见心
    2020-11-28 17:55

    I like the solution posted by user1786647, and I've updated it a little to change the timezone to a function argument and add optional support for passing either a Unix time or datetime string to use for the returned datestamp.

    It also includes a fallback for "setTimestamp" for users running version lower than PHP 5.3:

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

提交回复
热议问题