mardi 20 octobre 2020

What is the difference between compare two date as string with format (Y-m-d h:i:s) and two date with strtotime of date in php?

I have confused between two different conditions but gives the same result.

First Case

  $row_otp_time = '2020-10-20 01:59:31';

  $date = new DateTime($row_otp_time);
  $date->modify('+5 minute');
  $timezone = date_default_timezone_get();
  date_default_timezone_set($timezone);
  $expired_datetime = $date->format("Y-m-d h:i:s");

  $current_date_time = '2020-10-20 02:04:31'; //current date      

  if($current_date_time > $expired_datetime){
    echo 'expired';
  }
  else{
    echo 'not expired';
  }

Ouput not expired


Second Case

  $row_otp_time = '2020-10-20 01:59:31';

  $date = new DateTime($row_otp_time);
  $date->modify('+5 minute');
  $timezone = date_default_timezone_get();
  date_default_timezone_set($timezone);
  $expired_datetime = $date->format("Y-m-d h:i:s");

  $current_date_time = '2020-10-20 02:04:31'; //current date      

  if(strtotime($current_date_time) > strtotime($expired_datetime)){
    echo 'expired';
  }
  else{
    echo 'not expired';
  }

Output not expired

So in the above two examples, there is one difference is that in first case, I have compared the normal date as string but in the second case, I have compared the date with strtime function and I know that second method is proper to check.

But I want why the first case is not proper or can you explain in which type of cases or some dates example where that first case given improper result.

Aucun commentaire:

Enregistrer un commentaire