简体   繁体   English

检查两个日期之间的日期

[英]Check the date between two dates

I have to check if the incoming date is between 3 and 6 months before today. 我必须检查输入的日期是否在今天之前的3到6个月之间。 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. 收到的日期是20-02-2018-超出范围。
  2. Incoming date is 20-10-2017 - Inside Range. 接收日期为20-10-2017-内部范围。
  3. Incoming date is 20-08-2017 - Out of Range. 接收日期是20-08-2017-超出范围。

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))){ 说明:需要将条件从if((strtotime($date1) < strtotime($date2)) || (strtotime($date1) > strtotime($date3)))更改为if((strtotime($date1) <= strtotime($date2)) && (strtotime($date1) >= strtotime($date3))){

It's also significantly easier if you're using DateTime objects: 如果您使用DateTime对象,也将大大简化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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