-1

I have two datetime objects stored in my datebase through a contructor method: App\Entity\Token

    public function __construct()
{
    $this->creation = new \DateTime("now");
    $this->valid = (new \DateTime("now"))->modify('+1 day');
}

When i try to compare those objects with my datetimenow the result isn't as expected, tried many diferents situations, camparing < > or using diff between two dates. Shall i use something special?: Example:

    $datenow = new \DateTime("now");
    if ( $datenow < $creation && $datenow > $valid ) {
} else{result_always_here}

Could be something related with the format or i must use doctrine in order to compare it?

enter image description here

Thanks.

Kind regards.

CitizenG1
  • 185
  • 8
  • 21
  • Based on your sample code there though, your $datenow value (18:14:26) is newer than your creation attribute (17:56:23) – georaldc Apr 08 '19 at 18:25
  • 2
    A date can never be before a certain date *and* after that same date + 1 day... – jeroen Apr 08 '19 at 18:26
  • 1
    I get a sample datetime through my objects: $creation = $pledge->getCreation(); $valid = $pledge->getValid(); It returns the date and date+1 when de constructor build it. But doesn't matter when comparing those datetimes, because as i said, I retrieve this data through doctrine as any other object.I was trying to compare if a date is between in two dates, in this i only need compare if a datetime is grater than a valid time, so $datenow > $valid works as expected, altough i don't know why can't compare if datetime is between the other two dates. I'm doing something wrong i guess.Cheers. – CitizenG1 Apr 08 '19 at 18:40
  • In what way does Symfony change the behaviour? Please extract a [mcve] to determine whether it is actually relevant to your question. – Ulrich Eckhardt Apr 08 '19 at 19:47

1 Answers1

2

I'm not completely sure if I understand the situation correctly, but if you are trying to check if a date is in between two other dates, then your code from the example should look like that:

if ($datenow > $creation && $datenow < $valid ) {
    // Code here should be executed
} else{
    // result_always_here is no more
}

So, comparing DateTime objects can be done like you wanted, also to check if a date is between two others, it's just that your comparison operators are the other way around.

Michał Tomczuk
  • 531
  • 3
  • 10