-1

how to understand if one date in php is less than another minus one day? I mean if for example a date is set to "2018/07/03"; how can I understand if a given date is less than "2018/07/02"

date1 : year1/month1/day1 date2: year2/month2/day2

<?php
if ($year1 >= $year2) {
        if ($month1 >= $month2) {
                  if (($day1 - 1) > $day2) {
                      echo 'you could do something..';
                   }
          }
}
?>

the above code fails if forexample $year2 = 2017 and $month2 = 11.. can anybody help me? thanks a lot..

Shokouh Dareshiri
  • 826
  • 1
  • 12
  • 24

2 Answers2

2

Here, this should work.

$date_to_check = new DateTime($yesterday);
$today = new DateTime();
$time_diff = $today->diff($date_to_check)->d;

if($time_diff > 1) {
echo "This is greater than one day.";
}else{
echo "This is not greater than one day.";
tim
  • 677
  • 9
  • 11
1
$date = strtotime("2018/07/01");
$date2 = strtotime("2018/07/02");

if($date > $date2){
  print('date is bigger');
  // do stuff when date is bigger than date2
} else {
  // else ...
  print('date2 is bigger');
}

To convert string to date php has function named strtotime(). Compairing date objects is simple.

There is full information about strtotime() http://php.net/manual/ru/function.strtotime.php

Another way:

$date = new DateTime("2018/07/01");
$date2 = new DateTime("2018/07/02");


if($date->modify("+1day") > $date2){
  print('date is bigger');
  // do stuff when date is bigger than date2
} else {
  // else ...
  print('date2 is bigger or equal');
}

Notice modify modifies $date object itself.

Read more here http://php.net/manual/en/class.datetime.php

Community
  • 1
  • 1
Adizbek Ergashev
  • 732
  • 8
  • 17