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


当前回答

你可以使用下面的代码:

<?php
    $currentDateTime = date('Y-m-d H:i:s');
    echo $currentDateTime;
?>

其他回答

date_default_timezone_set('Europe/Warsaw');
echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");

Linux服务器时间与PHP time()时区差异如下:

<?php
    putenv("TZ=Asia/Kabul");
    $t = time();
    echo date('d/m/Y H:i:sa', $t);
?>

根据如何使用PHP获取当前日期时间(NOW)这篇文章,有两种常见的方法来获取当前日期。要在PHP中获取当前的日期时间(now),您可以在任何PHP版本中使用date类,或者在PHP >= 5.2中使用datetime类。

这里有各种日期格式表达式。

使用日期的示例

该表达式将以Y-m-d H:i:s格式返回NOW。

<?php
    echo date('Y-m-d H:i:s');
?>

使用datetime类的示例

该表达式将以Y-m-d H:i:s格式返回NOW。

<?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
?>
// 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.

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

我们可以使用date函数设置默认时区:

<?php
    date_default_timezone_set("Asia/Kolkata");
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
    echo "The time is " . date("h:i:sa");
?>