How to Get the Current Date and Time in PHP

For getting the current Date and Time in PHP, it is recommended to use the date() function or the DateTime() class.

This short tutorial will assist you in getting the current date and time in PHP. Below you can find the two options we recommend to use.

Watch a course Learn object oriented PHP

Applying the date() Function

The PHP date() function is capable of converting the timestamp, located in the computer memory in a readable format.

Let’s, first, check out the syntax of the date() function:

<?php

$timestamp = time(); // get the current timestamp
$date = date('Y-m-d H:i:s', $timestamp); // format the timestamp as a string in the desired format
echo $date; // output the formatted date and time

?>

Finally, the output you will get is as follows:

2020-02-02 08:22:26

Applying the DateTime() Class

An alternative and efficient way of getting the date and time is using the DateTime() class. Also, it is possible to apply functions for formatting the date and time in various ways.

Here is how to get the date and time with DateTime class:

<?php

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

?>

The output is something as follows:

2020-02-02 08:22:26

Describing Date and Time in PHP

The manipulation of date and time is an inevitable part of programming. To be able to work with data and time, one should be aware of the arsenal of the PHP tools.

Date and time functions allow getting the date and time from the server where PHP scripts run. These functions are applied for formatting date and time in various ways.