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:

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:

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.

Facebook Comments