简体   繁体   中英

how to understand if one date in php is less than another minus one day?

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..

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.";
$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM