Reputation: 2261
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;
}
Upvotes: 3
Views: 2898
Reputation: 1593
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.
Upvotes: 4
Reputation: 11340
Why don't you just compare dates as strings? It's quite simple.
$InsertTime = '2017-11-06 14:47';
$DbTime = '2017-11-06 14:47:44';
public function WithinMinCheck($InsertTime, $DbTime) {
return (strpos($DbTime, $InsertTime) === 0);
}
Upvotes: 1