如何获取 PHP 中的当前日期和时间?

2022-08-30 05:46:09

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


答案 1

时间将按您的服务器时间过去。一个简单的解决方法是在调用 date()time() 函数之前使用 date_default_timezone_set 手动设置时区。

在澳大利亚墨尔本,所以我有这样的东西:

date_default_timezone_set('Australia/Melbourne');

或者另一个例子是洛杉矶 - 美国

date_default_timezone_set('America/Los_Angeles');

您还可以通过以下方式查看服务器当前所在的时区:

date_default_timezone_get();

所以像这样:

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

因此,您问题的简短答案是:

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

然后所有时间都将是您刚刚设置的时区:)


答案 2
// 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.

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


推荐