我想做的是检查日期范围不能超过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;
}
?>
这是我的GUI
知道如何解决我的问题吗?感谢
答案 0 :(得分:5)
$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';
}
答案 1 :(得分: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
答案 2 :(得分:1)
如果年份发生变化,所提供的解决方案将无效,因为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;
}
答案 3 :(得分: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;
}