Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon check if time is within the same minute

I have datetime from a database and a datetime coming from an input='time' field.

I have one datetime without seconds (so it defaults to 00) and one with the seconds. I need to check if the two variables are in the same minute.

Example: for True

Carbon {#349 ▼
  +"date": "2017-11-06 14:47:00.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}
Carbon {#362 ▼
  +"date": "2017-11-06 14:47:44.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}

Example: for False

Carbon {#349 ▼
  +"date": "2017-11-06 14:48:00.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}
Carbon {#362 ▼
  +"date": "2017-11-06 14:47:44.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}

I have this going now but it will show within the 60 seconds mark. I'm having a hard time displaying if it's within the same minute.

$InsertTime = 2017-11-06 14:47
$DbTime = 2017-11-06 14:47:44


public function WithinMinCheck($InsertTime, $DbTime) {
   $WithinMin = "true";
   $InsertTime = Carbon::createFromFormat('Y-m-d H:i', $InsertTime);
   $DbTime = Carbon::createFromFormat('Y-m-d H:i:s', $DbTime);
   $difference = $InsertTime->diffInSeconds($DbTime);
   if ($difference >= 60) {
    $WithinMin = "false";
   } else {
    $WithinMin = "true";
   }

   return $WithinMin;
}
like image 355
ahinkle Avatar asked Nov 21 '25 05:11

ahinkle


1 Answers

Cant you just set the second field of the second timevariable to 0 and compare the values?

$newTime = $DbTime->copy()->second(00);
if($InsertTime->ne($newTime)) {
    $WithinMin = "false";
}
return $WithinMin;  //since $withinMin is set to true initially, it would only be false if Insertime is not equal

Keep in mind, that the above solution will only work if the minute value is the same. If the second time has a different minute value, no matter even if it is within 60 seconds of the first, it will return false.

like image 189
pseudoanime Avatar answered Nov 22 '25 19:11

pseudoanime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!