Days Until Christmas in PHP

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:

<?php

date_default_timezone_set('Australia/Brisbane');

STEP 2

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

<?php

date_default_timezone_set('Australia/Brisbane');

$christmasDay = strtotime('December 25');

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.

<?php

date_default_timezone_set('Australia/Brisbane');

$christmasDay = strtotime('December 25');

$time = time();

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:

<?php

date_default_timezone_set('Australia/Brisbane');

$christmasDay = strtotime('December 25');

$time = time();

$seconds = $christmasDay - $time;

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:

<?php

date_default_timezone_set('Australia/Brisbane');

$christmasDay = strtotime('December 25');

$time = time();

$seconds = $christmasDay - $time;
$minutes = $seconds / 60;
$hours = $minutes / 60;
$days = ceil($hours / 24);

echo "There are " . $days . " days until Christmas";

STEP 6

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

<?php

date_default_timezone_set('Australia/Brisbane');

$christmasDay = strtotime('December 25');

$time = time();

$days = ceil(($christmasDay - $time)/60/60/24);

echo "There are " . $days . " days until Christmas";

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

User Avatar

A nice little script for Christmas

by CD, 07-Dec-2016

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.