MGM
MGM

Reputation: 223

how to decrease months in php?

I want to separate 4 quarter months from current month.

$q1Start = date('Y-m-01',strtotime('-2 months'));
$q1End = date('Y-m-d');

$q2Start = date('Y-m-01',strtotime('-5 months'));
$q2End = date('Y-m-d',strtotime('-3 months'));

$q3Start = date('Y-m-01',strtotime('-8 months'));
$q3End = date('Y-m-t',strtotime('-6 months'));

$q4Start = date('Y-m-01',strtotime('-11 months'));
$q4End = date('Y-m-t',strtotime('-9 months'));

But its not showing the exact date.

I want like this.

2015-06-01
2015-08-31

2015-03-01
2015-05-31

2015-02-28
2014-12-01

2014-09-01
2014-11-30

How to decrease by current month? Thanks

Upvotes: 2

Views: 463

Answers (1)

Arjan
Arjan

Reputation: 9874

Since the quarters should be based on the current month, it's easier to start with the first day of the month for calculations.

$dayOfMonth = date('d');
$firstDayOfCurrentMonth = strtotime(sprintf('-%d days + 1 day midnight', $dayOfMonth));

$q1Start = date('Y-m-d', strtotime('-2 months', $firstDayOfCurrentMonth));
$q1End = date('Y-m-d', strtotime('+1 month - 1 day', $firstDayOfCurrentMonth));

$q2Start = date('Y-m-d', strtotime('-5 months', $firstDayOfCurrentMonth));
$q2End = date('Y-m-d', strtotime('-2 month - 1 day', $firstDayOfCurrentMonth));

$q3Start = date('Y-m-d', strtotime('-8 months', $firstDayOfCurrentMonth));
$q3End = date('Y-m-d', strtotime('-5 month - 1 day', $firstDayOfCurrentMonth));

$q4Start = date('Y-m-d', strtotime('-11 months', $firstDayOfCurrentMonth));
$q4End = date('Y-m-d', strtotime('-8 month - 1 day', $firstDayOfCurrentMonth));

This sets all variables to the expected values.

Upvotes: 4

Related Questions