How to get the current date and time in PHP?

哪个PHP函数可以返回当前日期/时间?


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 :)


    // Simply:
    $date = date('Y-m-d H:i:s');

    // Or:
    $date = date('Y/m/d H:i:s');

    // This would return the date in the following formats respectively:
    $date = '2012-03-06 17:33:07';
    // Or
    $date = '2012/03/06 17:33:07';

    /** 
     * This time is based on the default server time zone.
     * If you want the date in a different time zone,
     * say if you come from Nairobi, Kenya like I do, you can set
     * the time zone to Nairobi as shown below.
     */

    date_default_timezone_set('Africa/Nairobi');

    // Then call the date functions
    $date = date('Y-m-d H:i:s');
    // Or
    $date = date('Y/m/d H:i:s');

    // date_default_timezone_set() function is however
    // supported by PHP version 5.1.0 or above.

有关时区参考,请参阅支持的时区列表。


Since PHP 5.2.0 you can do it using OOP and DateTime() as well (of course if you prefer OOP):

$now = new DateTime();
echo $now->format('Y-m-d H:i:s');    // MySQL datetime format
echo $now->getTimestamp();           // Unix Timestamp -- Since PHP 5.3

And to specify the timezone :

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->getTimezone();
链接地址: http://www.djcxy.com/p/58522.html

上一篇: 检查请求是GET还是POST

下一篇: 如何在PHP中获取当前的日期和时间?