Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check the same date with PHP DateTime comparison operator

why this two dates doesn’t equal?

<?php

$a = new DateTime();
$b = new DateTime();
var_dump($a->format('d-m-Y H:i:s'));
var_dump($b->format('d-m-Y H:i:s'));
if ($a == $b) {
    echo "same";
}

i try PHP 8.1, 8.0 and 7.4 so i don’t think is a bug, maybe DateTime compare microseconds? If that’s so how i compare simple d-m-Y? Wihtout simply formatting and do a string comparison of course

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yeah there is a .000003 delay between each line of PHP hence == wont work because it’s not exactly the same

Example:

<?php
$a = new DateTime();
$b = new DateTime();
var_dump($a);
echo "<br>";
var_dump($b);

Output:

object(DateTime)#1 (3) { ["date"]=> string(26) "2022-06-19 15:26:56.020431" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
object(DateTime)#2 (3) { ["date"]=> string(26) "2022-06-19 15:26:56.020434" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }```
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading