简体   繁体   中英

Check the date between two dates

I have to check if the incoming date is between 3 and 6 months before today. If it is outside this range, it has to execute certain code.

below is the code

<?php

$date1 = '22-10-2017';
$date2 = date('d-m-Y' , strtotime('-3 months'));
$date3 = date('d-m-Y' , strtotime('-6 months'));
if((strtotime($date1) < strtotime($date2)) || (strtotime($date1) > strtotime($date3))){
    echo "Inside Range";
}else echo "Out of Range";

?>

For example if

  1. Incoming date is 20-02-2018 - Out of Range.
  2. Incoming date is 20-10-2017 - Inside Range.
  3. Incoming date is 20-08-2017 - Out of Range.

You are checking with || in your case you need to use && because you need date BETWEEN

$date1 = '20-08-2017';
$date2 = date('d-m-Y' , strtotime('-3 months'));
$date3 = date('d-m-Y' , strtotime('-6 months'));
if((strtotime($date1) <= strtotime($date2)) && (strtotime($date1) >= strtotime($date3))){
    echo "Inside Range";
}else { 
   echo "Out of Range";
}

Explanation: Need to change your condition from if((strtotime($date1) < strtotime($date2)) || (strtotime($date1) > strtotime($date3))) to if((strtotime($date1) <= strtotime($date2)) && (strtotime($date1) >= strtotime($date3))){

It's also significantly easier if you're using DateTime objects:

$date1 = new DateTime('20-08-2017');
$date2 = new DateTime('-3 months');
$date3 = new DateTime('-6 months');

if($date1 < $date2 && $date1 > $date3) {
    echo "Inside Range";
} else {
    echo "Out of Range";
}

You can do like this:

$today=date_create(date("Y-m-d"));
$date=date_create("2018-06-12");
$diff=date_diff($today,$date)->format("%a");

if ($diff > 90 && $diff < 180) {
    echo "Inside range";
}
else {
    echo "Out of range";
}

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