phphtmldatedatetime-formatphp-5.5

Date difference in PHP code does not execute


I have a code in PHP 5.5.11 where I am trying to do the following:

  1. Get today's date in a variable --> $today
  2. Calculate the end of month from a date in a form --> $st_dt_eom

if difference between these 2 dates is more than 5 days then execute a code. The code in the if condition below does not execute.


$today= date();

if($_POST['Submit']=='SAVE')
 {
    $st_dt=YYYYMMDD($_POST['st_dt'],"-"); 
    $st_dt_eom= datetime::createfromformat('YYYYMMDD',$st_dt);;
    $st_dt_eom->modify('last day of this month');
    $diff = $today->diff($st_dt_eom);
    $diffDays= intval($diff->format("%d")); //to get integer number of days

    if($diffDays>5){

     
     redirect("index.php");
     
}

}


Solution

  • An example:

    // 2022-12-19
    $today = date('Y-m-d');
    
    // $_POST['st_dt']
    $st_dt = '2022-12-31';
    
    function dateDiffDays($today, $st_dt)
    {
        $today_obj= DateTime::createfromformat('Y-m-d', $today);
        $st_dt_eom= DateTime::createfromformat('Y-m-d', $st_dt);
    
        $diff = $today_obj->diff($st_dt_eom);
    
        return $diff->days;
    }
    
    // int(12)
    $res = dateDiffDays($today, $st_dt);
    

    use var_dump to locate your bug.