In this beginner’s tutorial, I will show you how to get the current year using PHP. There are various ways to do this, so I will include a number of examples.
Getting the current year using PHP’s date function.
To get the current year using PHP’s date function, you can pass in the “Y” format character like so:
//Getting the current year using //PHP's date function. $year = date("Y"); echo $year;
The example above will print out the full 4-digit representation of the current year.
If you only want to retrieve the 2-digit format, then you can use the lowercase “y” format character:
$year = date("y"); echo $year;
The snippet above will print out 20 instead of 2020, or 19 instead of 2019, etc.
Using the DateTime object.
If you wish to use a more object-orientated approach, then you can use PHP’s DateTime object:
//Getting the current year //using DateTime. $currentDate = new DateTime(); //Get the year by using the format method. $year = $currentDate->format("Y"); //Print it out echo $year;
Here, we created a DateTime object and then retrieved the current year by passing the “Y” character in as the $format parameter.
To get the 2-digit format instead, you can use the lowercase “y” character:
//Getting the two-digit format of //the current year using DateTime $currentDate = new DateTime(); $year = $currentDate->format("y"); echo $year;
As you can see, both the date function and the DateTime object use the exact same format characters in this case.
Hopefully, you found this guide helpful!
Related articles: