哪个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();

其他回答

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

d -表示一个月中的第一天(01 ~ 31) m -代表一个月(01 ~ 12) Y -年份(四位数) l(小写“l”)-代表星期几 H -以小时为单位的24小时格式(00至23) H -以前导零表示的12小时格式(01到12) i -前导0的分钟(00到59) s -前导0的秒(00到59) a -小写的子午线前后(am或pm)

例子:

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

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)

另一种简单的方法是获取当前日期和时间的时间戳。使用mktime()函数:

$now = mktime(); // Return timestamp of the current time

然后您可以将其转换为另一种日期格式:

//// Prints something like: Thursday 26th of January 2017 01:12:36 PM
echo date('l jS \of F Y h:i:s A',$now);

更多的日期格式在这里: http://php.net/manual/en/function.date.php

你可以:

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

完整的格式选项请参见文档:https://www.php.net/manual/en/function.date.php