PHP: Days until next Christmas.

This is a short tutorial on how to calculate the number of days until next Christmas using PHP. To do this, we can either use the DateTime object or the strtotime function.

Calculating the days until Christmas using DateTime.

If you are using PHP version 5.3.0 or above, then you can use the DateTime object. Take a look at the following example:

//Today's date.
$today = new DateTime();

//Christmas Day.
$christmasDay = date("Y") . "-12-25";

//Have we already passed this year's Christmas Day?
if(date("m") == 12 && date("d") > 25){
    //Use next year's Christmas Day date.
    $christmasDay = (date("Y") + 1) . "-12-25";
}

//Create DateTime object for Christmas Day.
$christmasDay = new DateTime($christmasDay);

//Get the interval difference between the two dates.
$interval = $today->diff($christmasDay);

//Print out the number of days between
//now and the next Christmas.
echo $interval->days . ' days until next Christmas!';

In the PHP code above, we calculate the number of days that will pass between the current day and next Christmas. Once the big day arrives, $interval->days will output 0 days.

After the day passes, the code above will automatically switch to next year’s Christmas day. i.e. On the 26th of December, 2019, the code will start to countdown to the 25th of December, 2020.

This is a better approach because it means that you do not have to keep updating your code every year.

Using strtotime.

If you are stuck on an older version of PHP, then you can use the strtotime function:

//Current unix timestamp.
$today = time();

//The unix timestamp of Christmas Day.
$christmasDay = strtotime(date("Y") . "-12-25");

//Have we already passed this year's Christmas Day?
if(date("m") == 12 && date("d") > 25){
    //Use the timestamp for next year's Christmas Day.
    $christmasDay = strtotime((date("Y") + 1) . "-12-25");
}

//Get the number of seconds that will pass between now and the next Christmas day.
$differenceInSeconds = $christmasDay - $today;

//Convert those seconds into days by dividing the number by 86400.
$days = floor($differenceInSeconds / (60 * 60 * 24));

//Print it out.
echo $days . ' days will pass between now and next Christmas!';

In the example above, we calculated the Unix timestamp of each date before carrying out some simple math to determine the number of days that will pass. Note that we use 86,400 because that is the number of seconds in a day.

Further reading: Calculating the difference between dates in PHP.