In this tutorial, we are going to see how to get the current date and time in PHP.There is two option in which we can use any to show the date and time in various format.
1) date function 2) DateTime class
Let’s see one by one.
Using Date() Function
Date() function is used to format timestamp to readable date and time.
date(format, timestamp)
The given below example will show date time in (‘d-m-y h:i:s’) format.
<?php
// Return current date and time from the server
$currentDateTime = date('d-m-y h:i:s');
echo $currentDateTime ;
?>
The date and time returned according to the timezone set on the server. So, if you are not getting correct date and time using above code then you have to change your timezone setting.
We can easily show the current date in different ways.
- date(“Y/m/d”);
- date(“Y.m.d”);
- date(“Y-m-d”);
- date(“H:i:s”);
- date(“Y-m-d H:i:s”);
- date(“l”);
Characters that are commonly used for date
l – Represents the day of the week
d – Represents the day of the month (01 to 31)
m – Represents a month (01 to 12)
Y – Represents a year (in four digits)
Using DateTime Class
In this method, we create an object and then call to function by using it to get current and time in PHP.
<?php $now = new DateTime();
echo $now->format('Y-m-d H:i:s');
?>
Characters commonly used for time.
h – 12-hour format of an hour with leading zeros (01 to 12)
H – 24-hour format of an hour (00 to 23)
i – Minutes with leading zeros (00 to 59)
s – Seconds with leading zeros (00 to 59)
a – Lowercase ante meridiem and post meridiem (am or pm).
If you are not getting right date or time in PHP, it mean your timezone setting is not correct. Please read this tutorial and set your timezone first.
How to Set the Timezone in the php.ini File or PHP Script
You have learned how to get the current date and time in PHP and how to format the date and time. If you have any queries related to this tutorial, feel free to comment.