w3resource

PHP Date Exercises : Current month and previous three months


23. Current Month and Previous Three Months

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 :

Flowchart: Current month and previous three months

For more Practice: Solve these Related Problems:

  • Write a PHP script to output the current month and the three previous months in order, formatted as full month names.
  • Write a PHP function to return an array containing the current month and the three preceding months using DateTime arithmetic.
  • Write a PHP program to display the current month along with the abbreviated names of the last three months.
  • Write a PHP script to dynamically determine and print the current month and previous three months with numeric and text representations.

Go to:


PREV : Last 6 Months from Current Month.
NEXT : Increment Date by One Month.

PHP Code Editor:



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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.