How do I get the current date and time in PHP?

后端 未结 30 1593
孤城傲影
孤城傲影 2020-11-22 08:19

Which PHP function can return the current date/time?

相关标签:
30条回答
  • 2020-11-22 09:03
    date_default_timezone_set('Europe/Warsaw');
    echo("<p class='time'>".date('H:i:s')."</p>");
    echo("<p class='date'>".date('d/m/Y')."</p>");
    
    0 讨论(0)
  • 2020-11-22 09:04

    The time would go by your server time. An easy workaround for this is to manually set the timezone by using date_default_timezone_set before the date() or time() functions are called to.

    I'm in Melbourne, Australia so I have something like this:

    date_default_timezone_set('Australia/Melbourne');
    

    Or another example is LA - US:

    date_default_timezone_set('America/Los_Angeles');
    

    You can also see what timezone the server is currently in via:

    date_default_timezone_get();
    

    So something like:

    $timezone = date_default_timezone_get();
    echo "The current server timezone is: " . $timezone;
    

    So the short answer for your question would be:

    // Change the line below to your timezone!
    date_default_timezone_set('Australia/Melbourne');
    $date = date('m/d/Y h:i:s a', time());
    

    Then all the times would be to the timezone you just set :)

    0 讨论(0)
  • 2020-11-22 09:04

    If you are Bangladeshi, and if you want to get the time of Dhaka then use this:

    $date = new DateTime();
    $date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
    $get_datetime = $date->format('d.m.Y H:i:s');
    
    0 讨论(0)
  • 2020-11-22 09:08

    You can use this format also:

    $date = date("d-m-Y");
    

    Or

    $date = date("Y-m-d H:i:s");
    
    0 讨论(0)
  • 2020-11-22 09:09

    If you want a different timescale, please use:

    $tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
    $lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
    $nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);
    
    date_default_timezone_set("Asia/Calcutta");
    echo date("Y/m/d H:i:s");
    
    0 讨论(0)
  • 2020-11-22 09:11

    Another simple way is to take the timestamp of the current date and time. Use mktime() function:

    $now = mktime(); // Return timestamp of the current time
    

    Then you can convert this to another date format:

    //// Prints something like: Thursday 26th of January 2017 01:12:36 PM
    echo date('l jS \of F Y h:i:s A',$now);
    

    More date formats are here: http://php.net/manual/en/function.date.php

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