PHP Date Exercises : Increment date by one month
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](https://www.w3resource.com/w3r_images/php-date-exercise-24.png)
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics