PHP-使用PHP检查给定日期是否在未来20年内

PHP-使用PHP检查给定日期是否在未来20年内,php,date,strtotime,floor,Php,Date,Strtotime,Floor,我想用PHP检查给定的日期是否超过20年 到目前为止,我正在这样做: <?php $date = '2039-03-23'; if (floor((time() + strtotime($date)) / (60*60*24*365)) > 20) { echo "date is in future over 20 years..<br>"; } else { echo "date is in future but less than 20 years.&

我想用PHP检查给定的日期是否超过20年

到目前为止,我正在这样做:

<?php
$date = '2039-03-23';
if (floor((time() + strtotime($date)) / (60*60*24*365)) > 20)
{
    echo "date is in future over 20 years..<br>";
}
else
{
    echo "date is in future but less than 20 years.<br>";
}

您正在将现在的日期(
time()
)添加到
$date
,并在未来比预期更远的地方结束,因此:

floor((strtotime($date)-time()) / (60*60*24*365))
应该给你2039-03-23和现在的区别


注意,你可以有比现在低的日期,你应该考虑添加一个“日期是过去”的结果。

< P>你把现在的日期(<代码>时间()/代码>)添加到<代码> $DATE < /C>,并且在FUTURE中比预期的更进一步,因此:
floor((strtotime($date)-time()) / (60*60*24*365))
应该给你2039-03-23和现在的区别


请注意,你可以有比现在低的日期,你也许应该考虑增加一个“日期是过去”的结果。

< P>。我会使用
DateTime
-对象并处理以下内容:

//create the DateTime-Object with origin time
$dateOrigin = new DateTime('2027-03-23');
//create a new one with current time
$dateNow = new DateTime();
//Add 20 years to the current time object
$dateNow->add(new DateInterval("P240M"));

//compare them
if($dateNow < $dateOrigin) {
  echo "date is 20 or more years in the future";
} else {
  echo "date is not 20 or more years in the future";
}
//使用原始时间创建DateTime对象
$dateOrigin=新日期时间('2027-03-23');
//用当前时间创建一个新的
$dateNow=new DateTime();
//向当前时间对象添加20年
$dateNow->添加(新的日期间隔(“P240M”);
//比较它们
如果($dateNow<$dateOrigin){
echo“日期为未来20年或以上”;
}否则{
echo“日期不是未来20年或20年以上”;
}

工作。

虽然诺米斯的答案是正确的,但你的演讲看起来非常复杂和难看。我会使用
DateTime
-对象并处理以下内容:

//create the DateTime-Object with origin time
$dateOrigin = new DateTime('2027-03-23');
//create a new one with current time
$dateNow = new DateTime();
//Add 20 years to the current time object
$dateNow->add(new DateInterval("P240M"));

//compare them
if($dateNow < $dateOrigin) {
  echo "date is 20 or more years in the future";
} else {
  echo "date is not 20 or more years in the future";
}
//使用原始时间创建DateTime对象
$dateOrigin=新日期时间('2027-03-23');
//用当前时间创建一个新的
$dateNow=new DateTime();
//向当前时间对象添加20年
$dateNow->添加(新的日期间隔(“P240M”);
//比较它们
如果($dateNow<$dateOrigin){
echo“日期为未来20年或以上”;
}否则{
echo“日期不是未来20年或20年以上”;
}

正在工作。

如果您使用的是32位系统,则可能是;试着改用。我希望那时我还活着。我不想修复几十年前的代码:(在y2k期间已经够糟糕了;)对于任何日期(今天、明年日期等),它都在打印消息日期是未来20年以上。如果您使用的是32位系统,则可能是;试着改用。我希望那时我还活着。我不想修复几十年前的代码:(在y2k期间已经够糟糕了;)对于任何日期(今天、明年日期等),它都在打印消息日期是在未来20年内。是的,更可靠、更好,但学习起来有点复杂。你的答案是认真工作的方法。谢谢,它很有效,使用DateTime()对象是处理日期的好方法。@Nomis的确,它有点复杂,但我认为开始使用类永远都不为时尚早。是的,它更可靠、更好,但学习起来更复杂一点。您的答案是进行严肃工作的方法。谢谢,它很有效,使用DateTime()对象是处理日期的好方法。@Nomis确实有点复杂,但我认为开始处理类永远都不为时尚早。