php compare two dates, month and year only

I want to compare two dates -- just the month and the year -- to see if one falls before the other. This is what I have currently:

$monthyear = date("M Y"); 
$finish = date("M Y",strtotime($row->finish));
$start = date("M Y",strtotime($row->start));
if ($start <= $monthyear and $finish >= $monthyear) {
   do some stuff..
}

What I'm trying to do, in plain English: If the start date is before or during the current month, and the finish date is after or during the current month, then do some stuff.

However, what is happening is that it is, e.g., October 2015 is seen as falling AFTER May 2016 (i.e., it runs what's inside the brackets if the finish date is October 2015). From what I can tell, it is comparing the months only, rather than the month + the year.

Any idea how to do make these comparisons correctly?

Upvotes: 9

Views: 21380

Answers (2)

Murad Hasan
Murad Hasan

Reputation: 9583

You need to compare through strtotime.

$monthyear = strtotime(date("F Y")); 
$finish = strtotime("May 2016");
$start = strtotime("October 2015");
if($start <= $monthyear && $finish >= $monthyear){
    echo 'Inner';
}else{
    echo 'Outer';
}

Result must be Inner.

Upvotes: 0

Richard
Richard

Reputation: 1055

Change the format to 'Y-m' that is alphabetically comparable as 2 strings

$monthyear = date("Y-m"); 
$finish = date("Y-m",strtotime($row->finish));
$start = date("Y-m",strtotime($row->start));
if ($start <= $monthyear and $finish >= $monthyear) {
   do some stuff..
}

Upvotes: 12

Related Questions