Get Real Time Date and Time using JavaScript

Get Real Time Date and Time using JavaScript

Table of contents

No heading

No headings in the article.

So our topic is Get Real time date and Time using JavaScript.
Real time date and time is same time and date that we see at our computer,mobile or watch screen. We just once set the time on our devices and they gave us updated time whenever we see. So the question is how can we see such Real time date and Time on our web page.

Let’s accomplish Real-Time date and Time using JavaScript...

First we will create a demo page using HTML and CSS to visualize how our time and date will look like...let’s create a beautiful demo page.

<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Date and Time</title>
</head>
<style type="text/css">
    @import url('https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap');

    body{
        display: grid;
        min-height: 95vh;
        place-content: center;
        background: lightblue;
    }
    p{
        display: inline;
    }

    #time{
        font-size: 60px;
        color: #004AAD;
    }

    #day{
        font-size: 40px;
        color: #FF5757;
    }

    #date{
        font-size:20px;
        color: #FF5757;
    }

    main{
        font-family: 'Fredoka One', cursive;
    }

    .date{
        width: 70%;
        margin: 0 4em;
    }


</style>
    <body>
        <main>
            <div>
                <p id="time">10:30:00PM</p>
            </div>
            <div class="date">
                <p id="day">SUN</p>
                <p id="date">9 May 2021</p>
            </div>
        </main>
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

If we run our code until now it will look like this on our browser window.

We have just created a demo page. At this stage our current date and time will not change, it will always remain the same. So how can we get the real time date and time or you can say Live time and date? This we can achieve using JavaScript.

Let’s understand different portions of JavaScript code with steps...

Step#1: Call new Date() constructor

let currentTimeDate = new Date();

We have currentTimeDate object that will help us to get time and date...just wait and see how we get time and date with the help of currentTimeDate Object.

Step#2: Create array for weekday

let weekday = new Array(7);
        weekday[0] = "SUN";
        weekday[1] = "MON";
        weekday[2] = "TUE";
        weekday[3] = "WED";
        weekday[4] = "THU";
        weekday[5] = "FRI";
        weekday[6] = "SAT";

Current day will be picked from weekday array.

Step#3: Create an array for month

let month = new Array();
        month[0] = "JAN";
        month[1] = "FEB";
        month[2] = "MAR";
        month[3] = "APR";
        month[4] = "May";
        month[5] = "JUN";
        month[6] = "JUL";
        month[7] = "AUG";
        month[8] = "SEP";
        month[9] = "OCT";
        month[10] = "NOV";
        month[11] = "DEC";

Current month will be picked from month array.

Step#4: Get current hours

let hours   =  currentTimeDate.getHours();

We had created currentTimeDate object previously in Step#1. And now we are using dot operator along with getHours() to get current hour of time.

Step#5: Get current minutes

let minutes =  currentTimeDate.getMinutes();

we are getting current minutes of time using currentTimeDate.getMinutes() and saving these minutes in minutes variable.

let seconds = currentTimeDate.getSeconds();

similar to the previous paragraph we are getting seconds and saving them into seconds variable.

minutes = minutes < 10 ? '0'+minutes : minutes;

This line of code is just a way to properly organize our minutes because we don’t want to get 0,1,3 etc as minutes instead we want minutes as 00, 01, 03 etc.
This line of code just says, hey if minutes are less than 10 then append 0 with minutes and save minutes in minutes variable but if minutes are greater than 10 then do nothing and just save minutes in minutes variable.

seconds = seconds < 10 ? '0'+seconds : seconds;

Above statement is similar to minutes = minutes < 10 ? '0'+minutes : minutes;situation that we have discussed in previous paragraph. In minutes = minutes < 10 ? '0'+minutes : minutes;we have used js ternary operator. If anything is confusing we can also use old approach as shown in the following code block.

if(minutes < 10){
    minutes = '0' + minutes;
}else{
    minutes = minutes;
}

Step#6: Set AM and PM

let AMPM = hours >= 12 ? 'PM' : 'AM';

This statement just says, if hours are greater or equal to 12 then assign PM string to AMPM variable otherwise assign AM string to AMPM variable.

Step#7: Getting 12hr format

if(hours === 0){
    hours=12;
}else{
    hours = hours%12;
}

Here, We have used the if else statement to get 12hr time format.If hours will be equal to 0 then 12 will be assign to hours variable otherwise we will fall into else part of the condition and will tackle expression hours = hours%12;
hours = hours%12\===> here % is mod operator that will give us remainder. For example if hours are 13 then we will get 1,if hours are 14 then we will get 2, if hours will be 15 we will get 3 and so on.

Step#8: Get currentTime, currentDay, fullDate

let currentTime = `${hours}:${minutes}${AMPM}`;

Using JavaScript Template literals we are appending hours, minutes and AMPM values and saving whole string in currentTime variable.

let currentDay = weekday[currentTimeDate.getDay()];

currentTimeDate.getDay() gives us number value from 0-6, for example if current day is Sunday then currentTimeDate.getDay() will give us 0, if current day is Monday then currentTimeDate.getDay() will give us number 1 and so on for the rest of the days.
Now let’s say we get 0 by currentTimeDate.getDay(), let’s enter value 0 into our statement var currentDay = weekday[0]; Remember we have initialized weekday array before. So weekday[0] will give us value of 0index of weekday array(value is SUN) and the value will be saved in the currentDay variable.

let currentDate  = currentTimeDate.getDate();

This statement will give current date.

let currentMonth = month[currentTimeDate.getMonth()];

Similar to currentDay here we will get a number as a result of currentTimeDate.getMonth() , the number will be index of month array and we will access value according to corresponding index.

let CurrentYear = currentTimeDate.getFullYear();

Now here we will get current full year.

let fullDate = `${currentDate} ${currentMonth} ${CurrentYear}`;

Here we are appending currentDate, currentMonth, CurrentYear and making a complete string, this string then will be saved in fullDate variable.

Step#9: Change hard coded value of time, day and date using DOM

document.getElementById("time").innerHTML = currentTime;

Here value of currentTime variable is being saved into element that has id as time.

document.getElementById("day").innerHTML = currentDay;

Value of currentDay variable into element that has id as day.

document.getElementById("date").innerHTML = fullDate;

Save value of fullDate variable into element that has id as date.

Step#10: Get Real time Date and Time

setTimeout(getCurrentTimeDate);

setTimeout method calls a function after a number of milliseconds.

Step#11: Enclose code from Step#1 to Step#10 into a function getCurrentTimeDate

const getCurrentTimeDate = () => {

//Code from Step#1 to Step#10 will be here

}

Step#12: Call function getCurrentTimeDate

getCurrentTimeDate();

Step#10 to Step#12 might be confusing, please see whole code below for proper flow.

<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Date and Time</title>
</head>
<style type="text/css">
    @import url('https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap');

    body{
        display: grid;
        min-height: 95vh;
        place-content: center;
        background: lightblue;
    }
    p{
        display: inline;
    }

    #time{
        font-size: 60px;
        color: #004AAD;
    }

    #day{
        font-size: 40px;
        color: #FF5757;
    }

    #date{
        font-size:20px;
        color: #FF5757;
    }
    main{
        font-family: 'Fredoka One', cursive;
    }

    .date{
        width: 70%;
        margin: 0 4em;
    }


</style>
<body>

    <main>

        <div>
            <p id="time">10:30:00PM</p>
        </div>

        <div class="date">
            <p id="day">SUN</p>
            <p id="date">9 May 2021</p>
        </div>


    </main>

<script type="text/javascript">

    const getCurrentTimeDate = () => {
        let currentTimeDate = new Date();

        let weekday = new Array(7);
        weekday[0] = "SUN";
        weekday[1] = "MON";
        weekday[2] = "TUE";
        weekday[3] = "WED";
        weekday[4] = "THU";
        weekday[5] = "FRI";
        weekday[6] = "SAT";

        let month = new Array();
        month[0] = "JAN";
        month[1] = "FEB";
        month[2] = "MAR";
        month[3] = "APR";
        month[4] = "May";
        month[5] = "JUN";
        month[6] = "JUL";
        month[7] = "AUG";
        month[8] = "SEP";
        month[9] = "OCT";
        month[10] = "NOV";
        month[11] = "DEC";

        let hours   =  currentTimeDate.getHours();

        let minutes =  currentTimeDate.getMinutes();

        let seconds = currentTimeDate.getSeconds();
        minutes = minutes < 10 ? '0'+minutes : minutes;

        seconds = seconds < 10 ? '0'+seconds : seconds;

         let AMPM = hours >= 12 ? 'PM' : 'AM';

        if(hours === 0){

            hours=12;

        }else{
            hours = hours%12;
        }

        let currentTime = `${hours}:${minutes}:${seconds}${AMPM}`;
        let currentDay = weekday[currentTimeDate.getDay()];

        let currentDate  = currentTimeDate.getDate();
        let currentMonth = month[currentTimeDate.getMonth()];
        let CurrentYear = currentTimeDate.getFullYear();

        let fullDate = `${currentDate} ${currentMonth} ${CurrentYear}`;


        document.getElementById("time").innerHTML = currentTime;
        document.getElementById("day").innerHTML = currentDay;
        document.getElementById("date").innerHTML = fullDate;

        setTimeout(getCurrentTimeDate);

    }

    getCurrentTimeDate();

</script>
</body>
</html>

When our html page will load, we will get Real Time Date and Time.
Live: https://atif-dev.github.io/Real-Time_Date-Time-updated-/

This article is an updated form of an article written somewhere else.😇
Hope You Like it😇🙂.