0

i'm attempting to make an if statement to compare two time/dates and see if the second date is less than 24 hours after the first date entered. if it is it should not allow the statement to continue

$date is set earlier in the code and is the date being inputted by the user.

$now = new DateTime();
$future_date = new DateTime($date);

$interval = $future_date->diff($now);

//echo $interval->format("%d days, %h hours, %i minutes, %s seconds");

if ($interval > 60 * 60 * 24) {

here is the code i am attempting to use to compare if the date being given is the same, but i honestly don't really know how to even start this.

if ($interval > 60 * 60 * 24) {

edit: i don't really know if its actually working because no matter what it just comes up with a blank page.

  $BookID = $_GET['BookID'];
  $id = $_GET['id'];

 $query = mysqli_query($con,"SELECT time, date FROM tbl_booking WHERE BookID={$BookID} && tbl_mem_id={$id}");
$info = mysqli_fetch_assoc( $query);

$test = $info['date'] . $info['time'];

$date = date("Y-m-d H:i:s", strtotime($test));

$plus24hours = new DateTime("+1 day");
$future_date = new DateTime($date);



 if (isset($_SESSION['id']) && $_SESSION['id'] == $_GET['id']) {

 if (isset($_GET['BookID']) && is_numeric($_GET['BookID']))
 {

if ($future_date > $plus24hours) {

header("refresh:5;url=dashboard.php");
echo "Your booking has been cancelled.";   

$sql = "DELETE FROM `tbl_booking` WHERE `BookID`={$BookID}";
$result = mysqli_query($con, $sql);

 }}
 } else {
 // if id isn't set, or isn't valid, redirect back to view page
header("refresh:5;url=dashboard.php");
echo ("Sorry, there is less than 24 hours left and you cannot cancel.");


 }

2 Answers2

1

This is easier than you think. Just add 24 hours to the first date and then compare it to the future date. If the future date is less than the first date, it is less than 24 hours in the future.

$plus24hours = new DateTime("+1 day");
$future_date = new DateTime($date);

if ($future_date < $plus24hours) {
    // Less than 24 hours in the future
}
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

You can get the difference in seconds by converting the two DateTime objects to timestamps. $diffInSeconds = $future_date->getTimestamp() - $now->getTimestamp();

Maybe it would be better to use strtotime, if the DateTime objects are only required for this operation.

mcserep
  • 3,231
  • 21
  • 36