0

I have to compare datetime object with php, $availability is an array of dates that contains (from: 2017-07-24 16:20:08.000000 to 2017-07-25 16:20:08.000000) and when is 2017-07-23 16:20:08.000000.

/// when : 2017-07-23
$when = DateTime::createFromFormat( 'Y-m-d', '2017-07-23' );
// from : 2017-07-24 
$from = DateTime::createFromFormat( 'Y-m-d', '2017-07-24' );
// to : 2017-07-25 
$to   = DateTime::createFromFormat( 'Y-m-d', '2017-07-25' );
if ( $when >= $from && $when <= $to ) { echo $when . "is between from and to"; }

This doesn't work, or did I miss something?

How to compare objects from DateTime::createFromFormat? Is it possible, or do I have to strtotime?

  • 1
    Explain "Doesn't work".... you mean it displays the between message? – Mark Baker Jul 24 '17 at 16:32
  • 2
    `$when` is the 23rd, which is less than `$from` which is the 24th. So the first condition `$when >= $from` fails instantly. Also, you can't `echo $when;` - its an object, not a string. You'll need to use `$when->format("Y-m-d")` instead when echoing. – Qirel Jul 24 '17 at 16:33
  • `echo $when` will also get an error like `Object of class DateTime could not be converted to string` use `$when->format('YYYY-mm-dd')` – RiggsFolly Jul 24 '17 at 16:35
  • Maybe you should start by adding [error reporting](http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php/845025#845025) to the top of your file(s) _while testing_ right after your opening PHP tag for example ` – RiggsFolly Jul 24 '17 at 16:37
  • @Mark Baker, it means it doesn't display the between message. @ RiggsFolly, you're right, and surely i'm tired, i didn't fount that 23 lol, thanks for pointing this. –  Jul 24 '17 at 17:12

1 Answers1

0

Some issues:

1) The condition will fail given the inputs. Specifically, your $when object holds a time before your $from object (the day before). So, $when >= $from fails in the if statement.

2) The code within the if statement block would give an error. The variables created by the DateTime::createFromFormat() method are DateTime objects. You cannot echo out an object, it must be converted to a string, which can be done by using the DateTime class's format method. So rewrite the code within the if block as:

echo "{$when->format('Y-m-d')} is between {$from->format('Y-m-d')} and {$to->format('Y-m-d')}";
Lyle
  • 41
  • 3