NOW() function in PHP

前端 未结 20 1470
遥遥无期
遥遥无期 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:50

    My answer is superfluous, but if you are OCD, visually oriented and you just have to see that now keyword in your code, use:

    date( 'Y-m-d H:i:s', strtotime( 'now' ) );
    
    0 讨论(0)
  • 2020-11-28 17:51

    With PHP version >= 5.4 DateTime can do this:-

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

    See it working.

    0 讨论(0)
  • 2020-11-28 17:52

    MySQL function NOW() returns the current timestamp. The only way I found for PHP is using the following code.

    $curr_timestamp = date('Y-m-d H:i:s');
    
    0 讨论(0)
  • 2020-11-28 17:53

    Try this:

    date("Y-m-d H:i:s");
    
    0 讨论(0)
  • 2020-11-28 17:54

    You can use the PHP date function with the correct format as the parameter,

    echo date("Y-m-d H:i:s");
    
    0 讨论(0)
  • 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");
    }
    
    0 讨论(0)
提交回复
热议问题