Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php compare two dates, month and year only

Tags:

date

php

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?

like image 269
Christina Huggins Ramey Avatar asked May 17 '16 15:05

Christina Huggins Ramey


People also ask

How can I compare two dates in PHP?

Method 2: If both of the given dates are in different formats then use strtotime() function to convert the given dates into the corresponding timestamp format and lastly compare these numerical timestamps to get the desired result. echo "$date1 is older than $date2" ; ?>

How do you compare two different dates?

For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.

Can you compare time in PHP?

In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument. The diff() method will return a new object of type DateInterval .


1 Answers

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..
}
like image 83
Richard Avatar answered Sep 28 '22 03:09

Richard