PHP Date Exercises : Number of the month before the current month
20. Get Previous Month Number
Write a PHP script to get the number of the month before the current month.
Sample Solution:
PHP Code:
<?php
// Echoes the month of the date obtained by subtracting 1 month from the current date
echo date('m', strtotime('-1 month'))."\n";
?>
Output:
06
N.B.: The result may varry for your system date and time.
Explanation:
In the exercise above,
echo date('m', strtotime('-1 month'))."\n";: Outputs the month of the date obtained by subtracting 1 month from the current date.
- date('m', ...) formats the date to display only the month in two digits.
- strtotime('-1 month') calculates the timestamp representing the date and time one month ago from the current date.
- The result is echoed with a newline character ("\n") appended for formatting.
For more Practice: Solve these Related Problems:
- Write a PHP script to determine and display the numerical value of the month preceding the current month using DateTime functions.
- Write a PHP function that calculates the previous month from a given date and outputs the month number.
- Write a PHP program to compute the previous month number and handle edge cases when the current month is January.
- Write a PHP script that subtracts one month from today's date and then extracts and displays the month part as a number.
Go to:
PREV : Calculate Weeks Between Two Dates.
NEXT : Convert Seconds into Days, Hours, Minutes, Seconds.
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.