NOW() function in PHP

Keywords: PHP MySQL Unix

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

I know how to do this with date(), but I asked if there was a function for this only.

For example, return:

2009-12-01 00:00:00

#1 building

Use this feature:

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 building

Use PHP version > = 5.4 DateTime You can:

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

See it work .

#3 building

I like the solution released by user1786647 and updated it to change the time zone to a function parameter, and added optional support for passing Unix time or datetime strings for the timestamp returned.

It also includes "setTimestamp" backup for users running versions 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");
}

#4 building

Use strftime :

strftime("%F %T");
  • %F and% Y-%m-%d.

  • %T and% H:%M:%S.

This is about ideone Demonstration .

#5 building

Besides:

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

Posted by gray8110 on Thu, 23 Jan 2020 06:14:37 -0800