HTML, Javascript, and Telling the Time

Had a fun time tonight doing some really shitty and basic Javascript coding for giggles.  For some background info, we’ve got a bunch of monitors at work that show the status of most of our systems.  One of these monitors had a nice rectangular block with nothing in it, so I decided to add a clock to that block.  Up until this point, we’ve had to check our PCs or our phones to see what time it was down to the minute, and since analog is so last year, the wall clock was useless.

I originally found a sweet script on this website that hosted its own clocks on their server and you just dropped an iframe to link it on your site.  Worked great on my PC, until I found out the monitoring PCs run on super low-privileged accounts (for good reason) that have zero web access rights.  I had to figure out how to script this sumbitch locally.

Figured I’ll show the code first, then break it down.  Bear in mind this is ain’t pretty, I don’t plan on cleaning it up, and since it works I really don’t care about anything else:

<script type="text/javascript">
    window.onload = setInterval(clock,1000);

function addZero(i)
    {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
    }


function clock()
    {
    var d = new Date();
    
    var date = d.getDate();
    
    var month = d.getMonth();
    var montharr =["January","February","March","April","May","June","July","August","September","October","November","December"];
    month=montharr[month];
    
    var year = d.getFullYear();
    
    var day = d.getDay();
    var dayarr =["Sun","Mon","Tues","Wed","Thur","Fri","Sat"];
    day=dayarr[day];
    
    var hour = addZero(d.getHours());
    var min  = addZero(d.getMinutes());
    var sec  = addZero(d.getSeconds());

    var tz   = d.getTimezoneOffset();

    if (tz == 240) {
        var tze = "EDT";
    } else {
        var tze = "EST";
    }
  
    document.getElementById("date").innerHTML=day+", "+month+" "+date+", "+year;
    document.getElementById("time").innerHTML=hour+":"+min+":"+sec+" "+tze;
    }
</script>

<div style="font-size:500%" id="date" align="center"></div>
<div style="font-size:500%" id="time" align="center"></div>

So, let’s jump in with the beginning:

<script type="text/javascript">
    window.onload = setInterval(clock,1000);

Basically this is telling us that the following script is Javascript.  The second line says that when the window is loaded, call function clock every 1000 milliseconds, or every one second – which for a clock is the most we’ll need unless you planned on showing milliseconds on the page.

function addZero(i)
    {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
    }

This function is to fix the formatting of d.getHours() and the other Javascript methods to get the current time.  Those methods don’t care about formatting, so if the hour is 8 o’clock, their response is 8, not 08 like I needed.  This function basically says if whatever is entered for i is less than 10, then take the number zero, add i to the end of it, and return the whole thing as i.

For instance, addZero(8) will return 08.

function clock()
    {
    var d = new Date();
    
    var date = d.getDate();
    
    var month = d.getMonth();

Here we’re getting to the meat and potatoes of the script.  A new function, clock:

  • Assign variable d as the specified date and time, in our case since () is undefined, it becomes today’s exact date and time.  Specifically, new Date() creates a new date object.
  • Based on variable d, assign variable date as the current numerical date by using method d.getDate().  getDate() uses whatever variable is before the period to source it’s information, which then gets output to our new variable.  This number can be from 1-31.
  • Based on variable d, assign variable month as the current numerical month by using method d.getMonth().  getMonth() works the same way as above, outputting the numerical month based on whatever variable is before the period.  The only difference is the number starts at zero (so 0-11), not 1 like you would expect.
    var montharr =["January","February","March","April","May","June","July","August","September","October","November","December"];
    month=montharr[month];

Now we’re going to get kind of fancy with an array of month names.

  • Create an array called montharr.  The entries we supply (the names of the months) are input and assigned an index number starting at 0.  January get an index number of 0, December becomes 11.

Then we convert the variable month, which up to this point was numeric, and convert it to the word associated in the array:

  • Variable month becomes the output of montharr based on what the variable month currently is.
  • If the variable is 8 (the current month September), it looks at the array, sees index 8 corresponds to the word September, and then assigns the word September to that variable.

Sounds complicated, but it works.

    var year = d.getFullYear();
    
    var day = d.getDay();
    var dayarr =["Sun","Mon","Tues","Wed","Thur","Fri","Sat"];
    day=dayarr[day];

Assign the variable year as the full numeric year – ie 2017.  Easy peasy.

Now, another array.  Works the same way as above:

  • Variable day is assigned the numeric day of the week, starting at 0 and going to 6.
  • Create an array with the days of the week, in this case abbreviated.
  • Convert the variable day, which is currently numeric, to the corresponding array index, which is the word day of the week.
  • If the variable is 4 (the current day is Wednesday), it looks at the array, sees index 4 corresponds to the word Wednesday, and assigns the word Wednesday to that variable.
    var hour = addZero(d.getHours());
    var min  = addZero(d.getMinutes());
    var sec  = addZero(d.getSeconds());

Now, handling time is far, far easier than the above for our dates:

  • Variable hour becomes the result of our above mentioned addZero function when it is applied to the method to get the current hour.  If it’s 8 o’clock, it tacks on a zero and assigns it to the variable.
  • Repeat for the minute and second variable.
var tz   = d.getTimezoneOffset();

    if (tz == 240) {
        var tze = "EDT";
    } else {
        var tze = "EST";
    }

This part is kind of hacky because I didn’t care about other timezones except for Eastern.

  • Variable tz becomes the timezone offset in minutes.  Easy way to determine that is to take the number of hours we’re ahead or behind, and multiply by 60 – durr hurr.  In our case, since we’re EDT currently, it is four hours times 60, or 240 minutes.  If you’re ahead of GMT, the number becomes negative.
  • A sweet if/else statement.  If variable tz is equal to 240, then new variable tze becomes the word EDT.  If variable tz does not equal 240, then new variable tze becomes the word EST.

Doneski.  Now to put it all together into one string and end the script:

    document.getElementById("date").innerHTML=day+", "+month+" "+date+", "+year;
    document.getElementById("time").innerHTML=hour+":"+min+":"+sec+" "+tze;
    }
</script>

Element ID date is equal to the combination of the variables daymonthdate, and year.  Your formatting can change if you remember each variable has no spaces or punctuation, so if you need to add a coma or anything else, put them in quotes and between the plus signs.

Element ID time works the same way, by combining the variables hourminsec, and tze.

<div style="font-size:500%" id="date" align="center"></div>
<div style="font-size:500%" id="time" align="center"></div>

These two lines call the element IDs specified above, align them to center, and make them 500% larger than the page would normally load them.

Like I said in the beginning, this is real basic and kind of hacky.  There may be better or more streamlined ways to accomplish the same, but this worked pretty splendidly for what I needed.

I’m by no means a Javascript or HTML pro, but I know enough to get by and figure things out when I get stuck.

EDIT 9/29/17 @ 00:56 – I realized that on the timezone hacky shit, I only used one equal sign (=) instead of two (==) when checking to see if the timezone offset is 240 or not.  Javascript requires two in order to do a “this-equals-this” type of statement.  Noob status, you know.

Comment or be assimilated...

This site uses Akismet to reduce spam. Learn how your comment data is processed.