Reputation: 1103
What I want to do is check the date range cannot more than 6 months, else will return 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
Any idea how to solve my problem? thanks
Upvotes: 1
Views: 3944
Reputation: 6296
The solutions provided wont work if the year has changed as the diff() provides a structure with the various components
$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;
}
Upvotes: 2
Reputation:
$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';
}
Upvotes: 9
Reputation: 20753
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;
}
Upvotes: 0
Reputation: 10717
With diff
function
$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
Upvotes: 3