PHP Date Exercises : Current month and previous three months
PHP date: Exercise-23 with Solution
Write a PHP script to get the current month and previous three months.
Sample solition:
PHP Code:
<?php
// Output the current month and year
echo date("M - Y")."\n";
// Output the month and year for 1 month ago
echo date("M - Y",strtotime("-1 Month"))."\n";
// Output the month and year for 2 months ago
echo date("M - Y",strtotime("-2 Months"))."\n";
// Output the month and year for 3 months ago
echo date("M - Y",strtotime("-3 Months"))."\n";
?>
Output:
Jul - 2017 Jun - 2017 May - 2017 Apr - 2017
N.B.: The result may varry for your system date and time.
Explanation:
In the exercise above,
- echo date("M - Y")."\n";: Outputs the current month and year in the format "Month - Year".
- echo date("M - Y",strtotime("-1 Month"))."\n";: Outputs the month and year for 1 month ago using the strtotime function with the "-1 Month" argument.
- echo date("M - Y",strtotime("-2 Months"))."\n";: Outputs the month and year for 2 months ago using the strtotime function with the "-2 Months" argument.
- echo date("M - Y",strtotime("-3 Months"))."\n";: Outputs the month and year for 3 months ago using the "strtotime()" function with the "-3 Months" argument.
Flowchart :
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 last 6 months from the current month.
Next: Write a PHP script to increment date by one month.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/php-exercises/php-date-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics