0

I have saved a date in mysql table in date('Y-m-d H:i:s') format

$blacklisted_date = "2018-07-22 17:57:24";
$blacklisted_days = 7;
$now = date('Y-m-d H:i:s');

I want to add $blacklisted_days to $blacklisted_date

$result_date = $blacklisted_date + $blacklisted_days;

and then want to find the difference in days between the $result_date and $now.

$diff_days = $result_date - $now;
DMP
  • 523
  • 4
  • 19
  • 1
    Possible duplicate of [Adding days to $Date in PHP](https://stackoverflow.com/questions/3727615/adding-days-to-date-in-php) – Adrian W Jul 22 '18 at 16:45

2 Answers2

1

I believe this code block will help you solve the problem.

    $blacklisted_date = "2018-07-22 17:57:24";
    $blacklisted_days = 7;
    $now = date('Y-m-d H:i:s');
    $result_date = date('Y-m-d H:i:s', strtotime($blacklisted_date . '+'. $blacklisted_days.' days'));

    if( $result_date > $now ){
       $datediff = strtotime($result_date) - strtotime($now);  
    }else{
       $datediff = strtotime($now) - strtotime($result_date);
    }

    $diff_days = round( $datediff / (60 * 60 * 24));
Ahmed Numaan
  • 1,034
  • 1
  • 10
  • 26
0

You can do it easily using DateTime class, look here:

$blacklisted_date = "2018-07-22 17:57:24";
$blacklisted_days = 7;

$date1 = new DateTime($blacklisted_date); // blacklisted
$date1->add(new DateInterval("P{$blacklisted_days}D")); // add N days

$date2 = new DateTime(); // now
$interval = $date1->diff($date2); // get diff
echo $interval->days; // in days

I hope it's really clear to understand

MrSmile
  • 1,217
  • 2
  • 12
  • 20
  • Thank you @MrSmile, if `$blacklisted_date = "2018-07-22 00:00:00";` and `$date2 = new DateTime("2018-07-22 00:00:01");` because of this one second difference the result is `6`, I want if whole day passes the difference should be `6`. – DMP Jul 22 '18 at 15:15
  • @DMP, you can do some condition using other info from `$interval` array like hours. For example `if $interval->hours >= 22) { $total_days = $interval->days+1; }` or similar you want. check `print_r($interval)` and you'll get more useful data – MrSmile Jul 22 '18 at 15:23