How I can check if given date (ie. 4/2017) is within 6 months from now in future?
For example:
4/2017 true
8/2017 false
5/2017 true
I have now:
$datum = explode(': ', $given_date); // Separate date from string
$datum = str_replace('/', '-', $datum[1]); // Given format month/year
$datum = strtotime('01-'.$datum); // Given only month/year
$limit_datum = strtotime('+6 months');
But I'm tilted right now, and can't get how to compare it...
Using DateTime, it becomes very trivial:
$now = new DateTime();
$input = DateTime::createFromFormat('m/Y', '4/2017');
$diff = $input->diff($now); // Returns DateInterval
// m is months
$lessThanSixMonths = $diff->y === 0 && $diff->m < 6; // true
See DateInterval
and DateTime
.
You need to do something like this
$todayDate = time();
$date_6_months = strtotime("+6 months");
$givenDate = strtotime($date);
if ($givenDate > $todayDate && $givenDate < $date_6_months){
put your code
}
EDIT:I change my previous wrong script.In this one you can compare strings of two dates
$given_date= "...."; //set given date (m/Y)
$current_date = date("m/Y",mktime());
$month_given = strtok($given_date, '/');
$year_given = strtok('/');
$month_now = strtok($current_date, '/');
$year_now = strtok('/');
$diff_year = $year_given - $year_now;
$diff_month = $month_given - $month_now;
$our_diff = $diff_year * 12 + $diff_month;
if($our_diff <= 6 && $our_diff >= 0){
//less or equal than 6months
}
else if($our_diff > 6){
//more than sixmonths
}
else{
//negative number
}