PASSWORD RESET

Your destination for complete Tech news

PHP

How to add years to date in PHP?

447 0
< 1 min read

To add years to a date in PHP, you can use the DateTime class along with the DateInterval class. Here’s an example code snippet:

$date = new DateTime('2023-02-25'); // the date you want to add years to
$years_to_add = 2; // the number of years to add

$date->add(new DateInterval('P' . $years_to_add . 'Y'));

echo $date->format('Y-m-d');

In this example, we’re starting with a date of ‘2023-02-25’ and adding 2 years to it. The DateTime object is created using the initial date string.

The add() method is then called on the DateTime object with a new instance of the DateInterval class passed as an argument. The DateInterval object is constructed using the ‘P’ format specifier for a period of time, followed by the number of years to add, and the ‘Y’ format specifier for years.

Finally, the format() method is called on the DateTime object to format the resulting date string in the ‘Y-m-d’ format, which represents year, month, and day.

The output of the example code snippet will be ‘2025-02-25’, which is the original date with 2 years added to it.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.