I just want to compare 2 datetime objects to see if they are set to the same date, but I don't care about the time component of the the object. At the moment I am using the date_format command to extract strings like 'Y-m-d' to compare but this seems awkward.
$firstDate = date_format($firstDateTimeObj, 'Y-m-d'); $secondDate = date_format($secondDateTimeObj, 'Y-m-d'); if !($firstDate == $secondDate) { // some code }
I'm new to programming and PHP so any pointers appreciated.
php $dateOne = "2019-10-30"; $dateTwo = "2019-10-30"; echo "Date1 = $dateOne"; echo "\nDate2 = $dateTwo"; if ($dateOne == $dateTwo) echo "\nBoth the dates are equal!"; else echo "Both the dates are different!"; ?>
Use date_diff() Function to Get Time Difference in Minutes in PHP. We will use the built-in function date_diff() to get time difference in minutes. For this, we need a start date and an end date. We will calculate their time difference in minutes using the date_diff() function.
Use the object syntax!
$firstDate = $firstDateTimeObj->format('Y-m-d'); $secondDate = $secondDateTimeObj->format('Y-m-d');
You were very close with your if expression, but the ! operator must be within the parenthesis.
if (!($firstDate == $secondDate))
This can also be expressed as
if ($firstDate != $secondDate)
My first answer was completely wrong, so I'm starting a new one.
The simplest way, as shown in other answers, is with date_format
. This is almost certainly the way to go. However, there is another way that utilises the full power of the DateTime classes. Use diff
to create a DateInterval
instance, then check its d
property: if it is 0
, it is the same day.
// procedural $diff = date_diff($firstDateTimeObj, $secondDateTimeObj); // object-oriented $diff = $firstDateTimeObj->diff($secondDateTimeObj); if ($diff->format('%a') === '0') { // do stuff } else { // do other stuff }
Note that this is almost certainly overkill for this instance, but it might be a useful technique if you want to do more complex stuff in future.
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