Analog/Digital Clock – JavaScript – Part 8

Published on November 27, 2021 at 9:56 pm by LEW

Introduction

Now that we have completed the HTML and the CSS, it is time to work on the Java Script (JS) code that will make it all work. The code to make this work is not overly complex and the logic is straight forward.

Create the default.js file

If we take a look at our model from post 3 in this series, we see that we have three sections for our default.js file. Technically there are going to be a few more sections, but that is basically best practices. Our sections are going to be the following.

  1. Title/Comments
  2. Global Variable/Constant Declaration
  3. Main loop
  4. Current time function
  5. Move Analog Clock Hands Function
  6. Write Digital information function

Title Comment

A simple starting layout might look like this (don’t forget to use lots of comments).

/***********************************************
* Title: Program Title                         *
* Author: Your Name                            *
* Version: Version Number                      *
* Date: Today’s Date                           *
* Description:                                 *
***********************************************/

/* Global Variable Declarations */* Main loop code */

/* Functions */

// Return current time data

// Move analog hands

// Write digital information

Variable/Constant Declarations

As previously discussed in part 4, our variables will be for both date and time. We will create a constant array for the month names.

Since JS variables are loose, they do not get defined with a type (like integer, floating, or string). Rather the type is handled on the fly when a value is assigned. We will use “var” instead of “let”, as we will be assigning values latter. We will use “const” for our array and assign values, as it will not change.

My Global Variable section looks like this. Note the use of “//” for end of line comments.

/* Global Variable Declarations */

var date_time // hold current date and time

var current_hr // currrent hour

var current_min // currrent minute

var current_sec // currrent second

var current_day // currrent date

var current_month // currrent month

var current_year // currrent year

// set month_name array to be used with current_month

const month_name = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”

];

Main Loop

The main loop is where the program runs. We will set up an interval loop to run every second. The loop will execute our three functions, then wait for one second before repeating.

/* Main loop code */

setInterval(() => { // rerun code every second

    current_time ();

    movehands ();

    digitalinfo();

}, 1000);

Current Time Function

Our first function gets the system time, then breaks it down into the individual components (days, hours, etc). It is very straight forward using the new_date function.

// Return current time data

function current_time (){

   date_time = new Date();

   current_hr = date_time.getHours(); // 0-23 hours

   current_min = date_time.getMinutes(); // 0-59 minutes

   current_sec = date_time.getSeconds();// 0-59 seconds

   current_day = date_time.getDate(); // 1-31, dependent

   current_month = date_time.getMonth(); // 0-11 months

   current_year = date_time.getFullYear(); // 4 digit year

}

Move Analog Hands

This funciton is a little tricky, as we need to calculate rotational position from the time variables. This becomes somewhat more complicated as we do not want the hour hand to jump from hour to hour but track by minute.

Lets work out the math for the hour hand. There are 24 hours (0 – 23). However we are tracking twice around as the analog clock face only shows 12 hours. Therefore we get the hour position by multiplying by 30 (360 * 2 / 24 = 30). To track the minutes with the hour hand we have minutes divided by 2 (60 minutes is 30 degree arc between hours).

We use style.transform to change the rotation of the div with our specific IDs.

// Move analog hands

function movehands () {

   current_time ()

   // set rotational angle in degrees

   hr_rotation = 30 * current_hr + current_min / 2;

   min_rotation = 6 * current_min;

   sec_rotation = 6 * current_sec;

   // transform (rotate) div with matching IDs

   hour.style.transform = `rotate(${hr_rotation}deg)`;

   minute.style.transform = `rotate(${min_rotation}deg)`;

   second.style.transform = `rotate(${sec_rotation}deg)`;

}

Set the Digital Clock Display

There are a few calculations to perform for a couple of instances. For a uniform look, we want to add zero to numbers less than 10. We also have to distinguish between AM and PM. we are also using inline conditional statements (ternary operators). We use the document.geElementByID function to change the webpage content dynamically.

// Write digital information

function digitalinfo() {

   let period = “AM”;

   if (current_hr == 0) current_hr = 12;

   if (current_hr > 12) {

      current_hr = current_hr – 12;

      period = “PM”;

   }

   // Add zero to digital clock for numbers less than ten

   current_hr = current_hr < 10 ? `0${current_hr}` : current_hr;

   current_min = current_min < 10 ? `0${current_min}` : current_min;

   current_sec = current_sec < 10 ? `0${current_sec}` : current_sec;

   // Setup time and date strings

   let time = `${current_hr}:${current_min}:

   ${current_sec} ${period}`;

   let date = `${month_name[current_month]} ${current_day},

   ${current_year}`;

   // write time and date to digitalclock div for display

   document.getElementById(“digitaltime”).innerText = time;

   document.getElementById(“digitaldate”).innerText = date;

}

Conclusion

It has been a bit of a journey to get to this point. The remaining tasks in this project is testing. In this case it is best to test the Analog/Digitial clock in as many different browsers as possible.

After validating the code, you may want to do some personal customization. Try some different colors, use a different font, or change the lay out of the major blocks to vertical instead of horizontal. You are only limited by your imagination. Just remember to document and save older versions that you can go back and reference if you need to.

For your reference, my JavaScript file is attached below.

default JS File

Analog/Digital Clock – JavaScript – Part 1

Analog/Digital Clock – JavaScript – Part 2

Analog/Digital Clock – JavaScript – Part 3

Analog/Digital Clock – JavaScript – Part 4

Analog/Digital Clock – JavaScript – Part 5

Analog/Digital Clock – JavaScript – Part 6

Analog/Digital Clock – JavaScript – Part 7

Analog/Digital Clock – JavaScript – Part 8

Add New Comment

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