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

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.

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)

PHP provides a dedicated class DateTime for dealing with date and time. Most of people have been ignoring it, despite it has been available since PHP 5.2. Most of people have been ignoring it, despite it has been available since PHP 5.2.

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.

It seems like, due to changes in the DateTimeZone class in PHP 5.5, when creating a date and specifying the timezone as a a string like 'EDT', then getting the timezone from the date object and trying to use that to set the timezone on a date object you will have problems but never know it.

I think your approach is good, but I would remove the - as they do not add anything.

$firstDate = date_format($firstDateTimeObj, 'Ymd');
$secondDate = date_format($secondDateTimeObj, 'Ymd');

if ($firstDate != $secondDate) {
    // some code
}

There's a reason for ignoring the time zone when you pass a timestamp to __construct. That is, UNIX timestamps are by definition based on UTC. @1234567890 represents the same date/time regardless of time zone.

Searching for an answer with the same problem.. I arrived to this solution that's look better for me then use diff or other things.

The main problem was ignoring the time parts of object DateTime, just set it to a time, for example at 12:00:00

$firstDateTimeObj->setTime(12, 0, 0);
$secondDateTimeObj->setTime(12, 0, 0);

// The main problem was checking if different.. but you can use any comparison
if ($firstDateTimeObj != $secondDateTimeObj) {
}

The timestamp value represented by the DateTime object is not modified when you set the timezone using this method. Only the timezone, and thus the resulting display formatting, is affected. This can be seen using the following test code:

This worked great for me.

$date1=DateTime::createFromFormat('Y-m-d H:i:s', '2014-07-31 07:30:00')->format('Y-m-d');
$date2=DateTime::createFromFormat('Y-m-d H:i:s', '2014-08-01 17:30:00')->format('Y-m-d');
if($date1==$date2){
    echo "==";
}else{
    echo "!=";
}

Parameters object. Procedural style only: A DateTime object returned by date_create().The function modifies this object. modify. A date/time string. Valid formats are explained in Date and Time Formats.

A better way to get a nice time-format (1 year ago, 2 months until) without all the trailing months, days, hours, minutes, seconds in the result is by using the DateTime format and using the date_diff function as they both does most of the heavy lifting for you

Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when both the dates are in the same format but the problem arises when both dates are in a different format. Method 1: If the given dates are in the same format then use a simple comparison operator to compare the dates. Example:

In order to compare those two dates we use the method diff () of the first DateTime object with the second DateTime object as argument. The diff () method will return a new object of type DateInterval.

Comments
  • I'm sure that someone will come up with some clever manipulation of timestamps or something like that, but truly you've got the gist of it. Sorry that it's awkward...
  • Unfortunately PHP doesn't have a "gimme just the date" formatting option, so what you're doing is the best option.
  • What's wrong with it? Is it causing you an error? The only enhancement I can suggest would be to use the format() method on the objects directly.
  • Cheers. At least I'm now confident that I'm not unnecessarily complicating matters - PHP is doing that for me ;-)
  • By this way, you will not able to compare date (<, <=, > ...)
  • @TeChn4K: With DateTime objects, you will be.
  • And here's a link to the PHP documentation about comparing DateTime objects with <, == etc: php.net/manual/en/datetime.diff.php#example-2364. Of course, it doesn't solve the "ignoring time" part of the problem - set the times on both DateTime objects to be the same before comparing to solve that one.
  • You can also $diff=($d1->format("Ymd")-$d2->form("Ymd")). Its more consise.
  • @TeChn4K: please careful! ->format('Y-m-d') is for sure string - not DateTime - so $firstDate == $secondDate is a string comparison!
  • Maybe can you make clear "d" attribute ? (m : month; d, day; h, hour; i, minute; s, second;)
  • Actually this will not work in all cases. It is only effective if you are absolutely sure that both DateTime objects have the same time. Ex: If you have 2 date times, one with the time set to 2/11/2012 at 22:00:00 and the other set to 2/12/2012 at 20:00:00 it will be read as having the same day as there is less then 24 hours separating the times.
  • Coorect me if I'm wrong but this would not work if the datetime objects are separately by whole months. Ex: 2013-01-25 00:00:00 and '2013-02-25 00:00:00'