phpdatedynamically-generated

Year dynamically into date --- PHP


Does anyone know how to load current date data dynamically into a date in PHP ? In example: the year, to automatically update. I'm trying the following without success.

$nowDate = date('d/m/Y');
$cYear = date('Y');             
$dateBegin = DateTime::createFromFormat('d/m/Y', '01/01/'.$cYear);
$dateEnd = DateTime::createFromFormat('d/m/Y', '31/12/'.$cYear);

if ($nowDate >= $dateBegin && $nowDate <= $dateEnd)
{
  echo "is between";
} else {
    echo 'OUT!';
}

Solution

  • You can compare DateTime objects between each-other:

    $dateNow = new DateTime();          
    $dateBegin = new DateTime($dateNow->format('Y-01-01 00:00:00'));
    $dateEnd = new DateTime($dateNow->format('Y-12-31 23:59:59'));
    
    if ($dateBegin <= $dateNow && $dateNow <= $dateEnd) {
      echo "is between";
    } else {
        echo 'OUT!';
    }
    

    demo