Javascript - sort of works but is there a better way?
Posted: Fri 18 Mar 2011 12:31 am
I want to change the CSS stylesheet depending whether the sun is up or not (a dark background makes dim images easier to see), so I have a second "night time" CSS that I switch to depending on the time of day. What I have come up with works, but is somewhat messy. I use the Cumulus <#sunrise> parameter which uploads a formatted time like '07:40', which I then parse in Javascript to do the numerical comparison with hours and minutes of the current time. Is there a more elegant solution? [There is also a problem with time zones - see below]
Also, I have a concern that this only works in my own time zone - since Javascript uses the local clock on the viewing computer, I think. So, how do I specify the time zone of origin in Javascript?
DN
Code: Select all
var d = new Date();
var thours = d.getHours();
var tmins = d.getMinutes();
var sunrise = "<#sunrise>"; // this is replaced by Cumulus with eg '07:40'
var sunset = "<#sunset>"; // this is replaced by Cumulus with eg '18:35'
var srh = parseFloat(sunrise.slice(0,2)); // chop up string and turn into numbers
var srm = parseFloat(sunrise.slice(3));
var ssh = parseFloat(sunset.slice(0,2));
var ssm = parseFloat(sunset.slice(3));
if (((thours == srh && tmins > srm) || (thours > srh)) && ((thours < ssh) || (thours == ssh && tmins <= ssm)))
{ document.write("<link href='weatherstyle.css' rel='stylesheet' type='text/css' />"); }
else
{ document.write("<link href='weatherstyle_night.css' rel='stylesheet' type='text/css' />"); }
DN