I'm trying to see whether two DateTimeImmutable objects refer to the same calendar day, and I can't figure out why the code below does not work. Code is PHP.
function isSameDay( $x, $y ){
echo "<p>Comparing '" . $x->format('Y-m-d') . "' and '" . $y->format('Y-m-d'). "' returns";
if( $x->format('Y-m-d') == $y->format('Y-m-d)') ){
echo " true </p>";
return true;
}
echo " false </p>";
return false;
}
When testing, I'm getting the following output, where the top test case should be returning true:
Comparing '2021-09-06' and '2021-09-06' returns false
Comparing '2021-09-06' and '2021-10-29' returns false
Comparing '2021-09-06' and '2021-11-24' returns false
Comparing '2021-09-06' and '2021-11-26' returns false
My understanding is that DateTimeImmutable->format() returns a string, so the if statement is just a string comparison. In fact, the compare-as-strings approach seems to be one of the main approaches for comparing dates like this. For example, the comparison I use above is given as answers to several questions here:
What is the best way to find out if 2 dates are in same month in PHP?
Check if two PHP datetime objects are set to the same date ( ignoring time )