简体   繁体   中英

PHP Date Difference After 30 Days Error?

I have a date difference that works in minutes .. then after 1 hour goes to hours .. then after 24 hours goes to days .. then weirdly after 30 days it goes back to hours

For why?! What am I missing in this code or is this some bug?!

  $d_start = new DateTime('now');
  $d_end  = new DateTime($last_gdate);
  $d_dif = $d_start->diff($d_end);
  $d_d = $d_dif->d;
  $d_h = $d_dif->h;
  $d_m = $d_dif->i;
    if ($d_d < 1) {
      if ($d_h < 1) {
        $d_since = $d_m . "m";
      } else {
        $d_since = $d_h . "h";
      }
    } else {
      $d_since = $d_d . "d";
    }

You will notice that DateTime's diff() will restart d in the next month. You should use days if you are not going to check/honor m .

Code: ( Demo )

$last_gdate = "2018-07-23 00:01:02";
$d_start = new DateTime('now');
$d_end  = new DateTime($last_gdate);
$d_dif = $d_start->diff($d_end);
var_export($d_dif);
$d_d = $d_dif->days;
$d_h = $d_dif->h;
$d_m = $d_dif->i;
if ($d_d < 1) {
  if ($d_h < 1) {
    $d_since = $d_m . "m";
  } else {
    $d_since = $d_h . "h";
  }
} else {
  $d_since = $d_d . "d";
}

echo "\n$d_since";

Output:

DateInterval::__set_state(array(
   'y' => 0,
   'm' => 1,
   'd' => 0,
   'h' => 6,
   'i' => 42,
   's' => 2,
   'f' => 0.002468,
   'weekday' => 0,
   'weekday_behavior' => 0,
   'first_last_day_of' => 0,
   'invert' => 1,
   'days' => 31,
   'special_type' => 0,
   'special_amount' => 0,
   'have_weekday_relative' => 0,
   'have_special_relative' => 0,
))
31d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM