To get the current year in PHP, you can use the date
function with the 'Y'
format argument. This function returns the current date and time as a string, formatted according to a given format.
Here’s an example of how to use the date
function to get the current year:
$year = date('Y');
// $year is now the current year as a four-digit number, for example '2023'
You can also use the DateTime
class to get the current year. The DateTime
class provides more features and flexibility than the date
function, but it may be slower and more complex to use.
Here’s an example of how to use the DateTime
class to get the current year:
$datetime = new DateTime();
$year = $datetime->format('Y');
// $year is now the current year as a four-digit number, for example '2023'
Note that the date
function and the DateTime
class represent the current date and time in the default timezone of the server. If you need to work with the current date and time in a different timezone, you can use the setTimezone
method of the DateTime
class to set the desired timezone.
For example:
$datetime = new DateTime();
$datetime->setTimezone(new DateTimeZone('Europe/Paris'));
$year = $datetime->format('Y');
// $year is now the current year in the Paris timezone
You can also use the DateTimeImmutable
class to get the current year. This class is similar to the DateTime
class, but it creates immutable objects that cannot be modified after they are created. This may be useful if you want to ensure that the date and time cannot be changed by mistake.
For example:
$datetime = new DateTimeImmutable();
$year = $datetime->format('Y');
// $year is now the current year