Reputation: 33
I have the following if statement:
$current=date('d/m/Y');
$next_year=date('y')+1;
$q1a='01/04/'.date('Y');
$q1b='30/06/'.date('Y');
$q2a='01/07/'.date('Y');
$q2b='30/09/'.date('Y');
$q3a='01/09/'.date('Y');
$q3b='31/12/'.date('Y');
$q4a='01/01/20'.$next_year;
$q4b='31/03/20'.$next_year;
if (($current > $q1a) && ($current < $q1b))
{
$currentquarter='Q1';
}
elseif (($current > $q2a) && ($current < $q2b))
{
$currentquarter='Q2';
}
elseif (($current > $q3a) && ($current < $q3b))
{
$currentquarter='Q3';
}
elseif (($current > $q4a) && ($current < $q4b))
{
$currentquarter='Q4';
}
echo $currentquarter;
BUT its returning Q1 even though it should be Q3 as todays date falls between 01/09/2017 and 31/12/2017
Upvotes: 0
Views: 150
Reputation:
This would help you simplify the comparison to retrieve the current quarter.
function CurrentQuarter(){
$n = date('n');
if($n < 4){
return "1";
} elseif($n > 3 && $n <7){
return "2";
} elseif($n >6 && $n < 10){
return "3";
} elseif($n >9){
return "4";
}
}
Upvotes: 1
Reputation: 39
For date comparison in PHP you can use strtotime()
function
$date1 = '07/28/2018';
$date2 = '07/28/2017';
if(strtotime($date1) < strtotime($date2))
{
echo 'Date2 is greater then date1';
}
else
{
echo 'Date1 is greater then date2';
}
Upvotes: 2
Reputation: 522015
You're not comparing dates, you're lexically comparing strings. E.g.:
'21/03/2017' > '01/04/2017'
2
is larger than 0
, so this will be true. Character by character the first string sorts "larger than" the second. Again, it's a lexical comparison, not a numeric comparison.
At the very least you need to reverse the endianness to Y/m/d
to get the correct result; but you should really construct DateTime
objects or UNIX timestamps to do actual date/numeric comparisons properly.
Upvotes: 3