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

为了在 PHP 中获取当前日期和时间,建议使用 date() 函数或者 DateTime() 类。

此教程将在 PHP 中获取当前日期和时间。

使用 DateTime() 类

获取日期和时间的另一种有效方法是使用 DateTime() 类。
此外,可以以各种方式应用格式化日期和时间的功能。

以下是如何使用 DateTime 类获取日期和时间:

<?php
    $currentDate = new DateTime();
    echo $currentDate>format('Y-m-d H:i:s');
?>

输出如下:

2016-02-02 08:22:26

使用 date() 函数

PHP date() 函数能够以可读格式转换位于计算机内存中的时间戳。

让我们首先查看 date() 函数的语法:

<?php

    $currentDate = new date();
    echo $currentDate->format('Y-m-d H:i:s');
?>

最后,我们将得到的输出如下:

2016-02-02 08:22:26
日期:2020-06-02 22:15:49 来源:oir作者:oir