How to Get the Current Date and Time in PHP

  1. Applying the date() Function
  2. Applying the DateTime() Class
  3. Describing 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.

A. 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
 
    $currentDate = new date();
    echo $currentDate->format('Y-m-d H:i:s');
?>

Finally, the output you will get is as follows:

2020-02-02 08:22:26

B. 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 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.


Do you find this helpful?

Related articles