0

I am trying to perform some updates only if certains conditions are accomplish and one of them is related to comparison between two dates: one obtained from DB and returned by Symfony2 as a DateTime object and the second one get as string from a loop and transformed into a DateTime object.

This is the plain code I was testing:

$last = new \DateTime('2015-01-21T19:44:25.000Z');
$current = new \DateTime('2015-06-23 22:10:23');

if ($last > $current) {
    echo 'yes';
} else {
    echo 'no';
}

That outputs no. Now if I try to compare the same in OOP as follow:

$lastModifiedAt = new \DateTime($row['LastModifiedDate']);
$lastSyncAt = $entity->getLastSyncAt();

if ($lastModifiedAt > $lastSyncAt) {
    ....
}

This is the output of var_export($lastModifiedAt) and var_export($lastSyncAt):

DateTime::__set_state(array(
   'date' => '2015-06-16 19:23:41.000000',
   'timezone_type' => 2,
   'timezone' => 'Z',
))

DateTime::__set_state(array(
   'date' => '2015-06-24 07:35:14.000000',
   'timezone_type' => 3,
   'timezone' => 'America/Caracas',
))

The execution always enter on the condition, why? what I am doing wrong on the comparison?

EDIT

It's weird to me the behavior but perhaps the wrong is my code. Thanks to @marcin-orlowski I have run the following test also:

var_dump($lastModifiedAt == $lastSyncAt);
var_dump($lastModifiedAt > $lastSyncAt);
var_dump($lastModifiedAt < $lastSyncAt);

And this are the results:

bool(false)
bool(false) => this is the comparison I am doing
bool(true)

So comparison is right, perhaps something else at my code, anyway, thx

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

2 Answers2

2

There is an excellent library to handle DateTime related issues .. https://github.com/briannesbitt/Carbon . If the above mentioned case is not the only place you are handling DateTime , then I would consider investing sometime with Carbon.

Scalable
  • 1,550
  • 4
  • 16
  • 29
-2

You can use getTimestamp():

$date = new DateTime();
echo $date->getTimestamp();

And:

if ($last->getTimestamp() > $current->getTimestamp()) {
    echo 'yes';
} else {
    echo 'no';
}
Max Lipsky
  • 1,774
  • 1
  • 18
  • 29