Timed CSS Stylesheet Switch Using PHP Tutorial

Today I’m going to show you a pretty clever technique for changing the Cascading Style Sheet by time using PHP, this can be a quirky addon for region/country specific sites, and will allow you to experiment and perhaps alter the code to use for different purposes.

I have coded this so it uses 4 stylesheets and changes at 6am, 12pm, 7pm and 11pm.

The whole project is available to download and demo below, here I will break it down and explain its elements.

midday

The PHP Code that does the magic

<link rel="stylesheet" href="<?php

date_default_timezone_set("GMT"); // set to your time zone

$thetime = date("H"); // H means it just grabs the hour in 24 hour format

// this section grabs the correct stylesheet by time, don't alter if you can help it

if($thetime > 00 AND $thetime < 06) { echo "nighttime.css";} // between midnight and 6am
elseif($thetime > 05 AND $thetime < 12) { echo "morning.css";} // between 6am and 12pm
elseif($thetime > 11 AND $thetime < 19) { echo "midday.css";} // between 12pm and 7pm
elseif($thetime > 18 AND $thetime < 23) { echo "gettingdark.css";} // between 7pm and 11pm
elseif($thetime = 23) { echo "nighttime.css";} // 11pm
elseif($thetime = 00) { echo "nighttime.css";} // midnight
?>" type="text/css" media="screen" />

Timezone

Here we are setting the timezone by your location, im my example I have set it to the UK timezone (GMT)

This part is important as if not specified it will grab the server time, which means if the server isn’t based in your country the time will be inaccurate.

date_default_timezone_set("GMT"); // set to your time zone

You can alter this to your timezone, here is a list of supported timezones here: http://www.php.net/manual/en/timezones.others.php and http://php.net/manual/en/timezones.php

nighttime

Time

This part is straightforward and won’t need to be altered, basically it returns the hour in 24-hour format eg: 23

$thetime = date("H"); // H means it just grabs the hour in 24 hour format

The Main Part

This part makes it all work, using PHP it will grab the correct stylesheet dependant on time, you will notice a crossover on each setting (eg: < 12 then > 11 below), I have done it this way as if I didn’t it would not return a value (eg: < 12 then > 12)

if($thetime > 00 AND $thetime < 06) { echo "nighttime.css";} // between midnight and 6am
elseif($thetime > 05 AND $thetime < 12) { echo "morning.css";} // between 6am and 12pm
elseif($thetime > 11 AND $thetime < 19) { echo "midday.css";} // between 12pm and 7pm
elseif($thetime > 18 AND $thetime < 23) { echo "gettingdark.css";} // between 7pm and 11pm
elseif($thetime = 23) { echo "nighttime.css";} // 11pm
elseif($thetime = 00) { echo "nighttime.css";} // midnight

This section doesn’t need to be altered, but you can change the name of the stylesheets.

Scott Stevens

3 posts | 0 comments

Leave a Reply

Your email address will not be published. Required fields are marked *