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


当前回答

从PHP 5.2.0开始,你可以使用DateTime()类:

use \Datetime;

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

并指定时区:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->getTimezone();

其他回答

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

获取当前时间和日期的最佳方法是使用PHP中的date函数:

$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s

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

使用Unix时间戳:

$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s

设置服务器时区。

date_default_timezone_set('Asia/Calcutta');

这里有一个不同的时区列表。

PHP的date函数可以完成这项工作。

日期()

描述:

string date(string $format [, int $timestamp = time()])

返回根据给定格式字符串使用给定整数时间戳格式化的字符串,如果没有给出时间戳则返回当前时间。

例子:

$today = date("F j, Y, g:i a");               // March 10, 2001, 5:16 pm
$today = date("m.d.y");                       // 03.10.01
$today = date("j, n, Y");                     // 10, 3, 2001
$today = date("Ymd");                         // 20010310
$today = date('h-i-s, j-m-y, it is w Day');   // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y");             // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');   // 17:03:18 m is month
$today = date("H:i:s");                       // 17:16:18
$today = date("Y-m-d H:i:s");                 // 2001-03-10 17:16:18 (the MySQL DATETIME format)

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

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

您的国家时区:支持的时区列表

date_default_timezone_set('Asia/Kolkata');

$dateYmd = date('Y-m-d');
echo "Current Year Month Day: $dateYmd";

本年月日:2022-01-03

$datehms = date('h:i:s');
echo "Current Hour Minute Second: $datehms";

当前小时分秒:11:05:38