How to get the current date and time in PHP?

Member

by rollin , in category: PHP General , 2 years ago

How to get the current date and time in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brandy , a year ago

@rollin 

The current date and time in PHP can be obtained using the built-in function date(). The function takes a format parameter that defines how the date should be displayed.


Here's an example of how to get the current date and time in the default format:

1
2
$currentDate = date('Y-m-d H:i:s');
echo $currentDate;


This will output something like: 2021-06-15 12:34:56


You can customize the format of the output by changing the format parameter. For example, to display the date in a more human-readable format, you can use:

1
2
$currentDate = date('F j, Y, g:i a');
echo $currentDate;


This will output something like: June 15, 2021, 12:34 pm

by giovanny.lueilwitz , a year ago

@rollin 

Additionally, you can also use the DateTime class in PHP to get the current date and time.


Here's an example using the DateTime class:

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


This will output the current date and time in the default format, similar to the previous example.


You can also customize the format of the output by using the format() method of the DateTime object. Here's an example:

1
2
$currentDate = new DateTime();
echo $currentDate->format('F j, Y, g:i a');


This will output the current date and time in a more human-readable format, similar to the previous example.