Signup/Sign In

How to get current date and time in PHP

Answer: Using date() function

The PHP date() function is an in-built function that is used to format the date and time into human-readable form. With the help of the PHP date() function, we can get the current date and time in multiple formats. The multiple formats supported by the PHP date() function are given below:

  • 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”);

Where,

  • Y represents the year
  • m represents the month (1 to 12)
  • d represents the day of the month (1 to 31)
  • H represents the 24 hours format
  • i represents the minutes
  • s represents the seconds
  • l represents the day of the week

Example

This is an example of the current date in php.

<!DOCTYPE html>
<html>
<head>
	<title>PHP date and time</title>
</head>
<body>
	<?php
	$date = date('d-m-y h:i:s');
	echo $date;
	?>
</body>
</html>

Output


09-07-21 11:18:15

The output we get from the date() function is based on the server's default timezone setting. If we want to get the exact date and time, then we have to specify the timezone. To specify the timezone, we have to add the date_default_timezone_set() function just before the date function.

Example

This is an example of the current date with timezone in php.

<!DOCTYPE html>
<html>
<head>
	<title>PHP date and time</title>
</head>
<body>
	<?php
	date_default_timezone_set('Asia/Kolkata');
	$date = date('d-m-y h:i:s');
	echo $date;
	?>
</body>
</html>

Output


09-07-21 02:56:33

Conclusion

In this lesson, we have discussed how to get the current date and time in PHP. We can get the current date and time using the date() function. The date() function returns the date and time based on the server's default timezone. To get the actual date and time based on the user timezone, we have to add the date_default_timezone_set() function just before the date() function.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.