Avatar ·

How to calculate the difference between two dates in PHP: a detailed guide

Hi everyone! I'm a beginner in PHP and I've encountered a problem when working with dates. I need to calculate the difference between two dates in days, but I can't find the right way.\n\nI have two dates in the "Y-m-d" format, for example:\n- $date1 = "2023-01-15";\n- $date2 = "2023-02-20";\n\nI tried simply subtracting them, but it doesn't work because they are strings. Then I converted them to timestamp using strtotime() and subtracted, but the result is in seconds, and I'm not sure how to correctly convert it to days.\n\nHere's my current code, which gives strange results:\n\n```php\n$date1 = "2023-01-15";\n$date2 = "2023-02-20";\n$diff = strtotime($date2) - strtotime($date1);\necho $diff; // outputs 3110400 seconds\n$days = $diff / (60 * 60 * 24);\necho $days; // outputs 36 days, but it's not exact\n```\n\nI