I need to fetch previous month from the current month passed. Tried below code and it does work for the month having 30 days but does not work for specific months having 31 days viz. March, May, July, October and December
Note: The question may sound repeated, but please read it completely till the end. You can check the same issue by changing the system and testing below code against it. I need the previous month output in format Jul
For Date: 30-Jul
output is
Previous Month-Jun Current Month-Jul
For Date: 31-Jul
output is
Previous Month-Jul Current Month-Jul
$prev_month = date('M', strtotime("last month")); echo 'Previous Month--'.$prev_month; echo 'Current Month--'.date('M');
Also tried echo date('M', strtotime("-1 Months"));
but it outputs the same as above.
If current month is (August)
with 31
days and so previous month is (July)
with 31
days then it works and shows correct Previous Month ie July
, but it does not work if current month has 31
days and previous month has 30
or lesser days.
How should I go about it to fetch correct previous month on the basis of current month ?
You simply try as
echo "Previous Month".date('M',strtotime('first day of last month'));
and for specific date you can simply use
echo date('M',strtotime('first day of last month',strtotime('30-Jun')));//May
You should pass in the date from the start of the month.
$startDate = date('Y-m-1');
$prevMonth = date('M', strtotime("last month", strtotime($startDate)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.