DEV Community

Cover image for Get Real Time Date and Time using JavaScript
Atif Iqbal
Atif Iqbal

Posted on

Get Real Time Date and Time using JavaScript

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 get this...
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>Time and Date</title>
</head>
<style type="text/css">
    @import url('https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap');
    p{
        display: inline;
        margin: 5px;
    }

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

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

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


</style>
<body>

    <div>

        <p id="time">1:20PM</p>
        <p id="day">SUN</p>
        <p id="date">9 May 2021</p>

    </div>

</body>
</html>


Enter fullscreen mode Exit fullscreen mode

If we run our code until now it will look like this on our browser window
Alt Text
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 JavaScript portion of the code with steps...

Step#1: Call new Date() constructor



let currentTimeDate = new Date();


Enter fullscreen mode Exit fullscreen mode

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



var 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";


Enter fullscreen mode Exit fullscreen mode

Current day will be picked from weekday array.

Step#3: Create an array for month



var 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";


Enter fullscreen mode Exit fullscreen mode

Current month will be picked from month array.

Step#4: Get current hours



var hours   =  currentTimeDate.getHours();


Enter fullscreen mode Exit fullscreen mode

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



var minutes =  currentTimeDate.getMinutes();


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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 10then 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.
If this statement is confusing, you can use old approach that will be as



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


Enter fullscreen mode Exit fullscreen mode

Step#6: Set AM and PM



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


Enter fullscreen mode Exit fullscreen mode

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 === 12){
            hours=12;

    }else{

            hours = hours%12;

   }


Enter fullscreen mode Exit fullscreen mode

Here, We have used the if else statement to get 12hr time format.If hours will be equal to 12 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



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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(value is SUN) and the value will be saved in the currentDay variable.



var currentDate  = currentTimeDate.getDate();


Enter fullscreen mode Exit fullscreen mode

This statement will give current date.



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


Enter fullscreen mode Exit fullscreen mode

Similar to currentDay here we will get a number as a result of currentTimeDate.getMonth() and will access value from a index of month array.



var CurrentYear = currentTimeDate.getFullYear();


Enter fullscreen mode Exit fullscreen mode

Now here we will get current full year.



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


Enter fullscreen mode Exit fullscreen mode

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;


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

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

Step#10: Get Real time Date and Time



setTimeout(getCurrentTimeDate, 500);


Enter fullscreen mode Exit fullscreen mode

setTimeout function with value of 500 will change the value of our time after every minute by calling getCurrentTimeDate function.

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

}


Enter fullscreen mode Exit fullscreen mode

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>Time and Date</title>
</head>
<style type="text/css">
    @import url('https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap');
    p{
        display: inline;
        margin: 5px;
    }

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

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

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


</style>
<body>

    <div>

        <p id="time">1:20PM</p>
        <p id="day">SUN</p>
        <p id="date">9 May 2021</p>

    </div>

    <script type="text/javascript">

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

        var 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";

        var 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";

        var hours   =  currentTimeDate.getHours();

        var minutes =  currentTimeDate.getMinutes();
        minutes = minutes < 10 ? '0'+minutes : minutes;

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

        if(hours === 12){
            hours=12;

        }else{

            hours = hours%12;

        }

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

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

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


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

        setTimeout(getCurrentTimeDate, 500);

    }
    getCurrentTimeDate();

    </script>

</body>
</html>


Enter fullscreen mode Exit fullscreen mode

When our html page will load, we will get Real Time Date and Time. Just keep looking the page the time will increment automatically.
See live demo at https://atif-dev.github.io/javaScriptRealTimeDateTime/
Or at
https://codepen.io/Atitemp/pen/xxqGXOO
💻🙂👍

Top comments (2)

Collapse
 
yoursunny profile image
Junxiao Shi

ESLint is unhappy seeing all those var and new Array.
Also, minutes < 10 ? '0'+minutes : minutes could be written as minutes.toString().padStart(2,'0').

Collapse
 
valcech profile image
Vlastimil Slechta

Great article! Very helpful, easy to understand and learn from. Thank you 🙌