Last week, I wrote a short guide on how to get the current year in PHP. Today, I am going to show you how to get next year’s date using PHP.
Let’s start with the following example:
//Instantiate the DateTime object. $now = new DateTime(); //You can get next year's date by using the //DateTime::add function and DateInterval $nextYearDT = $now->add(new DateInterval('P1Y')); //Retrive the date in a YYYY-MM-DD format. $nextYear = $nextYearDT->format('Y-m-d'); //var_dump the result. var_dump($nextYear);
In the PHP code above, we:
- Created a new DateTime object.
- Afterwards, we provided the DateTime::add function with a DateInterval of P1Y. If we wanted to get a date that is 5 years into the future, we would have used P5Y as the interval instead.
- Finally, we retrieved the date in a YYYY-MM-DD format and did a var_dump on the result.
When I ran the above piece of code on the 14th of December, 2019, the result was: 2020-12-14
Note that if just want next year without the month or the day, then you can simply omit the “m” and “d” format characters:
//Get the date in a YYYY format. $nextYear = $nextYearDT->format('Y');
This will result in “2020” being printed out.
If you want to get next year’s date using PHP’s date and strtotime functions, then you can try the following example:
//Using date and the strtotime function $nextYear = date("Y-m-d", strtotime("+1 year")); var_dump($nextYear);
As you can see, we were able to pass in “+1 year” as a parameter to PHP’s strtotime function. The result of strtotime provided the date function with a Unix timestamp of next year’s date.
Related articles that you might find helpful: