Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two PHP datetime objects are set to the same date ( ignoring time )

Tags:

php

datetime

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.

like image 267
Dave Shaw Avatar asked Nov 30 '11 15:11

Dave Shaw


People also ask

How can I check if two dates are equal in PHP?

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!"; ?>

How can I get different time in PHP?

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.


2 Answers

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) 
like image 174
Evert Avatar answered Oct 14 '22 12:10

Evert


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.

like image 26
lonesomeday Avatar answered Oct 14 '22 10:10

lonesomeday