w3resource

PHP Date Exercises : Increment date by one month

PHP date: Exercise-24 with Solution

Write a PHP script to increment date by one month.

Sample date : 2012-12-21

Sample Solution:

PHP Code:

<?php
// Convert the date string "2012-12-21" to a Unix timestamp
$dt = strtotime("2012-12-21");

// Add 1 month to the given date using strtotime() function
// and output the result in the format "Y-m-d"
echo date("Y-m-d", strtotime("+1 month", $dt))."\n";
?>

Output:

2013-01-21

Explanation:

In the exercise above,

  • $dt = strtotime("2012-12-21");: Converts the date string "2012-12-21" to a Unix timestamp using the "strtotime()" function.
  • echo date("Y-m-d", strtotime("+1 month", $dt))."\n";: Adds 1 month to the given date using the "strtotime()" function with the "+1 month" argument, and then formats the result as "Year-Month-Day" using the "date(") function. Finally, it prints the resulting date.
  • Flowchart :

    Flowchart: Increment date by one month

    PHP Code Editor:

    Have another way to solve this solution? Contribute your code (and comments) through Disqus.

    Previous: Write a PHP script to get the current month and previous three months.
    Next: Write a PHP script to get the current date in Italian.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/php-date-exercise-24.php