简体   繁体   English

如何在php中检查日期范围超过6个月?

[英]How to check date range more than 6 months in php?

What I want to do is check the date range cannot more than 6 months, else will return false 我想做的是检查日期范围不能超过6个月,否则会返回false

here is my sample code 这是我的示例代码

<?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;
}
?>

here is my GUI 这是我的GUI

在此处输入图片说明

Any idea how to solve my problem? 知道如何解决我的问题吗? thanks 谢谢

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

With diff function 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;
}

Formats 格式

%y year
%m month
%d day

The solutions provided wont work if the year has changed as the diff() provides a structure with the various components 如果年份已更改,则提供的解决方案将不起作用,因为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'

The month calculation should be applied as : 本月计算应采用:

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

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

Try this - 尝试这个 -

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

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

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