Days Until Christmas in PHP

phplogo.jpg

In this short tutorial we will create a 'Days Until Christmas' script using PHP.

This script is fairly short and easy to understand but we will still break it down step-by-step.

STEP 1

The first thing to consider is the timezone of the server and the timezone of the user. There are various methods we can use to calculate the correct times.  However, to keep things simple we will assume this script will be placed on a website for Australian users and set a default timezone as follows:

STEP 2

Next, we need to define when Christmas Day is.  We can use the powerful strtotime() function as follows:

The variable $christmasDay will now hold the number of seconds from 01 January 1970 to 25 December this year.

STEP 3

We now need to know the current time in seconds.  We can use the time() function.

STEP 4

Now that we know the current time (in seconds) and the number of seconds unti 25 December, all we need to do is perform a simple subtraction:

STEP 5

We now have the number of seconds until 25 December.

However, we want the number of days.  Therefore, we need to divide by 60 to get the number of minutes.  Then we divide by 60 again to get the number of hours.  Then we divide by 24 to get the number of days.

We can also consider doing some form of rounding up using the ceil() function as follows:

STEP 6

We could tidy up lines 9 to 12 and write as a single line as follows: