Mohini
Mohini

Reputation: 268

how to get previous month date range in php

I want to get the previous months date range with PHP. I have tried below function to get last month's date range.

$last_month_start_date = date('Y-m-d',strtotime('first day of last month'));
$last_month_end_date = date('Y-m-d',strtotime('last day of last month'));
echo $last_month_start_date.' - '.$last_month_end_date;

Output: 2019-09-01 - 2019-09-30

but how can I get previous month's date range with PHP?

can anybody help me with this?

Upvotes: 0

Views: 884

Answers (2)

Vaibhavi S.
Vaibhavi S.

Reputation: 1093

To get Last to Last Month: If current month is October then below output gives first and last date of August

$last_to_last_start_date = $last_month_start_date = date('Y-m-d',strtotime('first day of last month -1 month')); 
// outout 2019-08-01

$last_to_last_end_date = $last_month_end_date = date('Y-m-d',strtotime('last day of last month -1 month')); 
// outout 2019-08-31

echo $last_to_last_start_date .' - '.$last_to_last_end_date ;
//Output : 2019-08-01 - 2019-08-31 

Upvotes: 1

Qirel
Qirel

Reputation: 26490

Create a date-time object that is two months behind, then use a modifier of first/last day of this month. The this month modifier works on the month of the object, so if the object's date is in August, it will look for the first and last days of August.

This means that you can provide any value for -2 months (like February, -1 month) and it will get the start and end-dates for that month.

$start = new DateTime("-2 months");
$end = clone $start;
$start->modify("first day of this month");
$end->modify("last day of this month");
echo $start->format("Y-m-d")." - ".$end->format("Y-m-d");

In October 2019, this outputs,

2019-08-01 - 2019-08-31

Upvotes: 0

Related Questions