This article demonstrates how to get the current year in PHP.

1. Using date() function

You can get the current year in PHP using the date() function. The single-arg date() function returns the current date according to the specified formatting string. To get the 4-digit numeric representation of a year, you can use the Y character in the format parameter string. Alternatively, to get a 2-digit representation of a year, you can use the y character.

Download  Run Code

 
If you need the year to be locale specific, you can use the strftime() function. It formats the time and date based on the locale specified with setlocale(). To get the 2-digit or 4-digit year representation, you can use the %y or %Y conversion specifier, respectively. However, the use of this function is deprecated with PHP 8.1.0. Also, the locale should be installed on your system, or this function won’t work as expected.

Download  Run Code

2. Using DateTime::format() function

Alternatively, you can get the DateTime object for the current date and call the DateTime::format() function with the format string Y or Y, which correspond to 4-digit and 2-digit numeric representations of a year, respectively.

Download  Run Code

 
You may also access the class member on instantiation in PHP. This feature was introduced with PHP 5.4 and comes in handy when you have to briefly access a class member and don’t need the object after that. Here’s a one-line invocation of the DateTime::format() function, where the format() member function is accessed on the same line as instantiating the DateTime class.

Download  Run Code

That’s all there is to getting the current year in PHP.