view raw
Christina Huggins Ramey Christina Huggins Ramey - 1 year ago 64
PHP Question

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?


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..