skip to Main Content

In my php have 2 strings representing dates in format "dd/mm/yyyy". I want to compare the second one with the firsth + 3 years. I tried this but returns me always the same response despite changing dates.

private function setBonus($s1, $s2) : string{
        $new_s1 = strtotime(str_replace('/', '-', $s1));
        $new_s2 = strtotime(str_replace('/', '-', $s2));
        $targetBonus = strtotime('+3 years', $s1);
        $targetBonus = strtotime('last day of May', $targetBonus);

        
        return (targetBonus > new_s2)? "YES" : "NO";
    }

If i insert error_log after the assignments of $new_s1, $new_s2 and $targetBonus this is what i have

$new_s1: 2016-08-29
$new_s2: 2022-07-22
$targetBonus: 2019-05-31

2

Answers


  1. Corrected it:

    private function setBonus($s1, $s2): string{
        $new_s1 = strtotime(str_replace('/', '-', $s1));
        $new_s2 = strtotime(str_replace('/', '-', $s2));
        $targetBonus = strtotime('+3 years', $new_s1);
        $targetBonus = strtotime('last day of May', $targetBonus);
    
        return ($targetBonus > $new_s2) ? "YES" : "NO";
    }
    

    Explained:
    Used $new_s1 instead of $s1 when calculating the target bonus date. Corrected the variable name to $targetBonus when setting the target bonus date. Used correct variable names in the return statement.

    Login or Signup to reply.
  2. As Luuk has already highlighted, your code has some issues – https://3v4l.org/8XLoE. You need to crank up your error_reporting().

    I would suggest:

    private function setBonus(string $s1, string $s2) : bool {
        $targetBonus = DateTime::createFromFormat('d/m/Y', $s1)
                            ->modify('+3 years')
                            ->modify('last day of May');
        $s2Date = DateTime::createFromFormat('d/m/Y', $s2);
    
        return $targetBonus > $s2Date;
    }
    

    This should probably have some validation of the argument values, or better would be to pass them around as DateTime or DateTimeImmutable, instead of strings.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search