Get current year in PHP
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.
|
1 2 3 4 |
<?php echo date("Y"), PHP_EOL; // 20XX echo date("y"), PHP_EOL; // XX ?> |
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.
|
1 2 3 4 5 6 |
<?php setlocale(LC_TIME, "de_DE"); echo strftime("%Y"), PHP_EOL; // 20XX echo strftime("%y"), PHP_EOL; // XX ?> |
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.
|
1 2 3 4 5 6 |
<?php $dt = new DateTime(); echo $dt->format("Y"), PHP_EOL; // 20XX echo $dt->format("y"), PHP_EOL; // XX ?> |
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.
|
1 2 3 4 |
<?php $date = (new DateTime)->format("Y"); echo $date; // 20XX ?> |
That’s all there is to getting the current year in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)