To get the current date in PHP, you can use the date()
function. This function returns a string representation of the current date and time, based on a format string that you specify.
Here is an example of how to use the date()
function to get the current date in the format "Y-m-d"
(year-month-day):
<?php
$date = date('Y-m-d');
echo $date; // Outputs something like "2022-12-24"
The date()
function takes the format string as its first argument and an optional timestamp as its second argument. If you don’t specify a timestamp, the current date and time will be used by default.
The format string can contain a variety of special characters that represent different parts of the date and time, such as Y
for the year, m
for the month, d
for the day, and H
for the hour. You can find a complete list of available format characters in the PHP documentation:
Alternatively, you can use the DateTime
class to get the current date and time in an object-oriented way. The DateTime
class provides a variety of methods for manipulating and formatting dates and times.
Here is an example of how to use the DateTime
class to get the current date and time:
<?php
$datetime = new DateTime();
echo $datetime->format('Y-m-d H:i:s'); // Outputs something like "2022-12-24 12:34:56"
The DateTime
class also provides a number of constants that you can use to get the current date and time in different formats, such as DATE_ATOM
for Atom format, DATE_ISO8601
for ISO 8601 format, and DATE_RFC822
for RFC 822 format.
Here is an example of how to use the DateTime
class constants to get the current date and time in different formats:
<?php
$datetime = new DateTime();
echo $datetime->format(DateTime::ATOM); // Outputs something like "2022-12-24T12:34:56+00:00"
echo $datetime->format(DateTime::ISO8601); // Outputs something like "2022-12-24T12:34:56+0000"
echo $datetime->format(DateTime::RFC822); // Outputs something like "Fri, 24 Dec 22 12:34:56 +0000"