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


当前回答

时间会随着服务器时间流逝。一个简单的解决方法是在调用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());

那么所有的时间都将是你刚刚设置的时区:)

其他回答

如果你是孟加拉国人,如果你想知道达卡的时间,那么用这个:

$date = new DateTime();
$date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
$get_datetime = $date->format('d.m.Y 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.

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

Use:

$date = date('m/d/Y h:i:s a', time());

它的工作原理。

非常简单的

date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());

下面是一些常用的表示时间的字符:

H -以前导零表示的12小时格式(01到12) i -前导0的分钟(00到59) s -前导0的秒(00到59) a -小写的子午线前后(am或pm)

确定你的时区

<?php
    date_default_timezone_set("America/New_York");
    echo "The time is " . date("h:i:sa");
?>

看看这个(可选)

<?php
    $d = mktime(11, 14, 54, 8, 12, 2014);
    echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

为日期

<?php
    echo "Today is " . date("Y/m/d") . ;
    echo "Today is " . date("Y.m.d") . ;
    echo "Today is " . date("Y-m-d") . ;
    echo "Today is " . date("l");
?>

下面是一些常用来表示日期的字符:

d -表示一个月中的第一天(01 ~ 31) m -代表一个月(01 ~ 12) Y -年份(四位数) l(小写“l”)-代表星期几

Source-W3-Schools