1

So I'm having some trouble comparing two times, and I wanted to see if someone might be able to assist me:

So I have the following first modified date/time:

Debug::dump($global_post->modified);

Which returns:

string(19) "2022-07-26T18:06:42"

Then I have my second modified time which is this:

$post = static::get_by_corporate_id($global_post->id);
$post_modified_date = $post->get_post_modified();

Which returns:

string(19) "2022-07-26 18:06:41"

Now I'm attempting to utilize the DateTime:diff() method to compare $global_post->modified and $post_modified_date and return true if they match, otherwise, return false.

How would I be able to reliable compare them when they are formatted differently?

theMap
  • 43
  • 5
  • Parse them first https://stackoverflow.com/a/6239199/529282, of course, you need to know the exact format used, otherwise, you can't tell if 2022-02-07 means July 2nd, 2022 or February 7th, 2022. – Martheen Jul 27 '22 at 03:00
  • @Martheen, how would you parse the first one with the `T` (timezone) inside the string? – theMap Jul 27 '22 at 03:01

2 Answers2

2

Simply by doing this, for example:

$date1 = new DateTime('2022-07-26T18:06:42');
$date2 = new DateTime("2022-07-26 18:06:41");
dd($date1 == $date2); //boolean
Ork Sophanin
  • 138
  • 6
1

I will create new dates from character strings:

$date = new DateTime('2022-07-26T18:06:42');
echo $date->format('Y-m-d H:i:s').PHP_EOL;

$date2 = new DateTime('2022-07-26 18:06:41');
echo $date2->format('Y-m-d H:i:s').PHP_EOL;

Then:

if( $date->format('Y-m-d H:i:s') == $date2->format('Y-m-d H:i:s') ) {
    echo 'yes';
    return true;
}
Monnomcjo
  • 715
  • 1
  • 4
  • 14