Coding challenge #1 (beginner level) - Creating a clock


Topic: Coding challenge #1 (beginner level) - Creating a clock
Published 06.02.2019 Updated 18.02.2019

Michal Szymanski posted 2 weeks ago

Introduction

In this tutorial, you will learn how to create a clock.

SEE THE FINAL RESULT

You will learn how to get, format and display date and you will practice your javascript fundamentals - like variables, functions, arrays and conditional statements.

Note 1: The clock isn't the most important here. We will use it as a practical example, which let you practice your basic javascript knowledge.

Note 2: For purpose of this tutorial, I have complicated a bit this example. There are ways to write it faster, shorter and simpler. But then you wouldn't learn a many important things.


MDB Coding Challenge

This tutorial is part of the MDB Coding Challenge.

It is an initiative that helps novice programmers learn programming through practical examples and creative challenges.

LEARN MORE ABOUT MDB CODING CHALLENGE

Requirements

To follow this tutorial you need a basic knowledge of HTML, CSS and JavaScript .

If you don't know these technologies or you would like to repeat the knowledge about them, I recommend you to read our previous tutorials first.

They are short, simple and free.

START HTML TUTORIAL START CSS TUTORIAL START JAVASCRIPT TUTORIAL

Let's get started!

Step 1 - myTimer function.

In the beginning, we create an empty function myTimer(). All the logic of our small program we'll write inside.

function myTimer() {

}

Step 2 - new Date(); object

To get the current date and time we use new Date() method. It will create a new date object with the current date and time.

Then we assign it to the variable.

Note: We declare a variable with a keyword let, what is feature of ECMAScript 2015 (which is a version of JavaScript). If you want to learn more about it read our tutorial JavaScript let variable.

function myTimer() {

    // creates a new date object with the current date and time
    let today = new Date();

}

Step 3 - getDay() method

We use a getDay() method. It returns the weekday of a date as a number (0-6). We assign its value to the day variable.

function myTimer() {
    // creates a new date object with the current date and time
    let today = new Date();

    // returns the weekday of a date as a number (0-6)
    let day = today.getDay();
}

Step 4 - daylist array

getDay() returns only a number of a weekday. It's not enough for us, because we want to display the full name of each weekday.

To achieve this, we have to create an array with the collection of names of weekdays.

function myTimer() {
    // creates a new date object with the current date and time
    let today = new Date();

    // returns the weekday of a date as a number (0-6)
    let day = today.getDay();

    // arrays with the list of weekdays
    let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
}

Now we can use the number contained in the variable day to define which name from the daylist array we want to display.

For testing purpose, you can use console.log method and open the console to see if it display a correct day.

console.log (daylist[day]);

If everything is ok, remove console.log statement.

Step 5 - getHours()getMinutes() and getSeconds()

To get a full date and time we also need hours, minutes and seconds.

getHours()getMinutes() and getSeconds() methods let us get necessary data:

function myTimer() {
    // creates a new date object with the current date and time
    let today = new Date();

    // returns the weekday of a date as a number (0-6)
    let day = today.getDay();

    // arrays with the list of weekdays
    let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];

    // returns the hours of a date as a number (0-23):
    let hour = today.getHours();

    // returns the minutes of a date as a number (0-59):
    let minute = today.getMinutes();

    // returns the seconds of a date as a number (0-59):
    let second = today.getSeconds();
}

Step 6 - AM and PM

AM stands for 'ante meridiem', which means 'before noon' in Latin.

PM stands for 'post meridiem', which means 'after noon' in Latin.

To display a date in this format we will use a conditional statement if.

First, we declare a variable and then we write the conditional statement which defines what value and under what condition it will have.

function myTimer() {
    // creates a new date object with the current date and time
    let today = new Date();

    // returns the weekday of a date as a number (0-6)
    let day = today.getDay();

    // arrays with the list of weekdays
    let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];

    // returns the hours of a date as a number (0-23):
    let hour = today.getHours();

    // returns the minutes of a date as a number (0-59):
    let minute = today.getMinutes();

    // returns the seconds of a date as a number (0-59):
    let second = today.getSeconds();

    // declare an empty variable
    let meridiem;

    // define, when it should be "PM" and when "AM"
    if (hour >= 12) {
        meridiem = "PM";
    } else {
        meridiem = "AM";
    };
}

Step 7 - Correction of formatting

Right now our timer will display hours like 18 PM, what isn't correct. It should be 6 PM of course.We can easly fix it by writing another simple conditional statement.

Another problem we should solve is displaying minutes and second. Right now it's possible that our timer will display time like that:

12 PM : 7 : 3

Doesn't look very good. We rather want something like:

12 PM : 07 : 03

This is how we fix it:

function myTimer() {
    // creates a new date object with the current date and time
    let today = new Date();

    // returns the weekday of a date as a number (0-6)
    let day = today.getDay();

    // arrays with the list of weekdays
    let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];

    // returns the hours of a date as a number (0-23):
    let hour = today.getHours();

    // returns the minutes of a date as a number (0-59):
    let minute = today.getMinutes();

    // returns the seconds of a date as a number (0-59):
    let second = today.getSeconds();

    // declare an empty variable
    let meridiem;

    // define, when it should be "PM" and when "AM"
    if (hour >= 12) {
        meridiem = "PM";
    } else {
        meridiem = "AM";
    };

    // Correction of formatting
    if (hour >= 13) {
        hour = hour - 12
    };
    if (minute < 10) {
        minute = "0" + minute;
    };
    if (second < 10) {
        second = "0" + second;
    };
}

Step 8 - gathering everything together

We have everything we need. It's time to gather all of the data together and store it in the single variable.

let timer = "Today is " + daylist[day] + "
"
+ hour + meridiem + " : " + minute + " : " + second

We also need to define a place where we want to display the date. We'll create a div with an id = demo and then we'll put our date inside.

<div id="demo"></div>
document.getElementById('demo').innerHTML = timer;

After all it should look like this:

<div id="demo"></div>

  <script>

    function myTimer() {
        // creates a new date object with the current date and time
        let today = new Date();

        // returns the weekday of a date as a number (0-6)
        let day = today.getDay();

        // arrays with the list of weekdays
        let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];

        // returns the hours of a date as a number (0-23):
        let hour = today.getHours();

        // returns the minutes of a date as a number (0-59):
        let minute = today.getMinutes();

        // returns the seconds of a date as a number (0-59):
        let second = today.getSeconds();

        // declare an empty variable
        let meridiem;

        // define, when it should be "PM" and when "AM"
        if (hour >= 12) {
            meridiem = "PM";
        } else {
            meridiem = "AM";
        };

        // Correction of formatting
        if (hour >= 13) {
            hour = hour - 12
        };
        if (minute < 10) {
            minute = "0" + minute;
        };
        if (second < 10) {
            second = "0" + second;
        };

        let timer = "Today is " + daylist[day] + "
"
+ hour + meridiem + " : " + minute + " : " + second document.getElementById('demo').innerHTML = timer; }
</script>

Step 9 - invoking the function

We have placed the entire code inside myTimer function, so it will not execute until we call it.

The problem is, if we just call the function it will render the time and it will stay static. It will not change it with every second, as we expect it to do.

Try it. Call the myTimer function and see the result.

myTimer();

We can solve it by using setInterval() method.

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

1000 ms = 1 second

So, if we call myTimer function like this, everything works as expected.

setInterval(myTimer, 1000);

The entire code looks like this:

<div id="demo"></div>

  <script>

    function myTimer() {
        // creates a new date object with the current date and time
        let today = new Date();

        // returns the weekday of a date as a number (0-6)
        let day = today.getDay();

        // arrays with the list of weekdays
        let daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];

        // returns the hours of a date as a number (0-23):
        let hour = today.getHours();

        // returns the minutes of a date as a number (0-59):
        let minute = today.getMinutes();

        // returns the seconds of a date as a number (0-59):
        let second = today.getSeconds();

        // declare an empty variable
        let meridiem;

        // define, when it should be "PM" and when "AM"
        if (hour >= 12) {
            meridiem = "PM";
        } else {
            meridiem = "AM";
        };

        // Correction of formatting
        if (hour >= 13) {
            hour = hour - 12
        };
        if (minute < 10) {
            minute = "0" + minute;
        };
        if (second < 10) {
            second = "0" + second;
        };

        let timer = "Today is " + daylist[day] + "
"
+ hour + meridiem + " : " + minute + " : " + second document.getElementById('demo').innerHTML = timer; } setInterval(myTimer, 1000);
</script>

Styling

To create a beautiful page with a background image we will use MDBootstrap library.

Note: I am not going to explain here how does it exactly works. If you are new to MDBootstrap follow our previous tutorial. There I explain in details every aspect of MDBootstrap, Bootstrap and Responsive Web Design in general.

MDBOOTSTRAP FULL TUTORIAL

Creating an intro

<!--Main Navigation-->
<header>

    <!--Mask-->
    <div id="intro" class="view">

        <div class="mask rgba-black-strong">

            <div class="container-fluid d-flex align-items-center justify-content-center h-100">

                <div class="row d-flex justify-content-center text-center">

                    <div class="col-md-10">

                        <!-- Heading -->
                        <h2  id="demo" class="display-4 font-weight-bold white-text pt-5 mb-2"></h2>

                    </div>

                </div>

            </div>

        </div>

    </div>
    <!--/.Mask-->

</header>
<!--Main Navigation-->

Note, that we add id="demo" to the central heading. We will display our date there.

Adjusting the styles

html,
body,
header,
#intro {
    height: 100%;
}

#intro {
    background: url("https://mdbootstrap.com/img/Photos/Horizontal/Nature/full%20page/img%20%285%29.jpg")no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

The entire code is available here:

FINAL CODE
Write
Please insert min. 20 characters.