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?
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" ; ?>
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.
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 .
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..
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With