0

我想要做的是检查日期范围不能超过 6 个月,否则将返回 false

这是我的示例代码

<?php
$date_string1 = "2013-01-01";
$date_string2 = "2013-08-01";
$date1 = date('Y-m-d',strtotime($date_string1));
$date2 = date('Y-m-d',strtotime($date_string2));

if ($date1 and $date2 range more than 6 months, so will){
   return false;
}else{
   return true;
}
?>

这是我的图形用户界面

在此处输入图像描述

知道如何解决我的问题吗?谢谢

4

4 回答 4

7
$date1 = DateTime::createFromFormat('Y-m-d', "2013-01-01");
$date2 = DateTime::createFromFormat('Y-m-d', "2013-08-01");
$interval = $date1->diff($date2);
$diff = $interval->format('%m');

if($diff > 6){
 echo 'false';
}else{
 echo 'true';
}
于 2013-08-26T07:35:20.987 回答
3

diff功能

$date1 = new DateTime('2013-01-01');
$date2 = new DateTime('2013-08-01');

$diff = $date1->diff($date2);
$month = $diff->format('%m'); // 7

if ($month > 6){
   return false;
}else{
   return true;
}

格式

%y year
%m month
%d day
于 2013-08-26T07:33:47.520 回答
2

如果年份发生变化,则提供的解决方案将不起作用,因为 diff() 提供了具有各种组件的结构

$date1 = new DateTime('2017-10-02');
$date2 = new DateTime('2017-08-01');

$diff = $date1->diff($date2);
echo $diff->y;   // prints '0'
echo $diff->m;   // prints '2'
//
$date1 = new DateTime('2017-10-02');
$date2 = new DateTime('2016-10-01');
$diff = $date1->diff($date2);
echo $diff->y;   // prints '1'
echo $diff->m;   // prints '0'

月份计算应应用为:

$diff = $date1->diff($date2);
$monthsDiff = $diff->y * 12 + $diff->m

if (monthsDiff > 6){
   return false;
}else{
   return true;
}
于 2017-03-27T23:29:14.023 回答
0

试试这个 -

$diff = abs(strtotime($date2) - strtotime($date1));

//$years = floor($diff / (365*60*60*24));
//$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
//$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

if ($diff > 5184000) // more than 6 months
{
  return false;
}
else
{
  return true;
}
于 2013-08-26T07:33:53.513 回答