NOW() function in PHP

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

    The PHP equivalent is time(): http://php.net/manual/en/function.time.php

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

    I was looking for the same answer, and I have come up with this solution for PHP 5.3 or later:

    $dtz = new DateTimeZone("Europe/Madrid"); //Your timezone
    $now = new DateTime(date("Y-m-d"), $dtz);
    echo $now->format("Y-m-d H:i:s");
    
    0 讨论(0)
  • 2020-11-28 17:44

    Or you can use DateTime constants:

    echo date(DateTime::W3C); // 2005-08-15T15:52:01+00:00
    

    Here's the list of them:

    ATOM = "Y-m-d\TH:i:sP" ;               // -> 2005-08-15T15:52:01+00:00
    COOKIE = "l, d-M-Y H:i:s T" ;          // -> Monday, 15-Aug-2005 15:52:01 UTC
    ISO8601 = "Y-m-d\TH:i:sO" ;            // -> 2005-08-15T15:52:01+0000
    RFC822 = "D, d M y H:i:s O" ;          // -> Mon, 15 Aug 05 15:52:01 +0000
    RFC850 = "l, d-M-y H:i:s T" ;          // -> Monday, 15-Aug-05 15:52:01 UTC
    RFC1036 = "D, d M y H:i:s O" ;         // -> Mon, 15 Aug 05 15:52:01 +0000
    RFC1123 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
    RFC2822 = "D, d M Y H:i:s O" ;         // -> Mon, 15 Aug 2005 15:52:01 +0000
    RFC3339 = "Y-m-d\TH:i:sP" ;            // -> 2005-08-15T15:52:01+00:00 ( == ATOM)
    RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ; // -> 2005-08-15T15:52:01.000+00:00
    RSS = "D, d M Y H:i:s O" ;             // -> Mon, 15 Aug 2005 15:52:01 +0000
    W3C = "Y-m-d\TH:i:sP" ;                // -> 2005-08-15T15:52:01+00:00
    

    For debugging I prefer a shorter one though (3v4l.org):

    echo date('ymd\THisP'); // 180614T120708+02:00
    
    0 讨论(0)
  • 2020-11-28 17:44

    There is no built-in PHP now() function, but you can do it using date().

    Example

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

    You can use date_default_timezone_set() if you need to change timezone.

    Otherwise you can make use of Carbon - A simple PHP API extension for DateTime.

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

    Use strftime:

    strftime("%F %T");
    
    • %F is the same as %Y-%m-%d.

    • %T is the same as %H:%M:%S.

    Here's a demo on ideone.

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

    If you want to get time now including AM / PM

    <?php 
        $time_now = date("Y-m-d h:i:s a");
        echo $time_now;
    ?>
    

    It outputs 2020-05-01 05:45:28 pm

    or

    <?php 
        $time_now = date("Y-m-d h:i:s A");
        echo $time_now;
    ?>
    

    It outputs 2020-05-01 05:45:28 PM

    0 讨论(0)
提交回复
热议问题