Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 4059

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T08:29:08+00:00 2024-11-26T08:29:08+00:00

Digital Clock using JavaScript

  • 61k

Hello readers,

In this article, you will learn how to design a simple animated Digital Clock in JavaScript. A digital clock or watch in which the hours, minutes, and sometimes seconds are indicated by digits, as opposed to an analog clock, where the time is indicated by the positions of rotating hands.

Let's get started

Prerequisite

  • Basic knowledge of HTML
  • Basic knowledge of CSS
  • Basic knowledge of JavaScript

It's Time to Code!

To create a digital clock first, you need to create three files one HTML File(index.html), the second one is CSS file(style.css) and the third one is JS file(index.js).

HTML code

index.html

  <!DOCTYPE html> <html lang="en">   <head>     <meta charset="utf-8">     <title>Digital Clock</title>     <link rel="stylesheet" href="style.css">   </head>     <body>         <!--Display day information e.g Wednesday March 12,2021-->         <div id="dayIntro">             <p id="dayName"></p>         </div>         <div class="container">             <!-- Display time -->             <div class="dispClock">                 <div id="time"></div>             </div>         </div>         <script src="index.js"></script>     </body> </html>   
Enter fullscreen mode Exit fullscreen mode

CSS Code

style.css

  /* Google font */ @import url('https://fonts.googleapis.com/css?family=Orbitron');  *{     margin: 0;     padding: 0;    }   html,body{     display: grid;     place-items: center;    }   #dayIntro {     font-size: 40px;     font-weight: 600;     letter-spacing: 3px;     border: 7px solid rgb(17,129,134);     border-radius: 10px;     margin: 20px;     font-family: 'Times New Roman', Times, serif;     padding: 15px;     background: linear-gradient(180deg, #a8b9d3,rgb(173, 227, 229)); }   .container{     height: 120px;     width: 550px;     position: relative;     background: linear-gradient(135deg, #14ffe9, #ffeb3b, #ff00e0);     border-radius: 10px;     cursor: default;    }   .container .dispClock,   .container {     position: absolute;     top: 28%;     left: 50%;     transform: translate(-50%, -50%);   }   .container .dispClock{     top: 50%;     height: 105px;     width: 535px;     background: linear-gradient(147deg, #000000 0%, #2c3e50 74%);     border-radius: 6px;     text-align: center;   }   .dispClock #time{     line-height: 85px;     color: #fff;     font-size: 70px;     font-weight: 600;     letter-spacing: 1px;     font-family: 'Orbitron', sans-serif;     background: linear-gradient(135deg, #14ffe9, #ffeb3b, #ff00e0);     -webkit-background-clip: text;     -webkit-text-fill-color: transparent;    }   
Enter fullscreen mode Exit fullscreen mode

JavaScript Code

Now here comes the main part. The entire code for the working of the clock is written within the currentTime() function.

Let's discuss everything step by step:-

Step 1:- Create a function currentTime().

  function currentTime() {   //code to be executed }   
Enter fullscreen mode Exit fullscreen mode

Step 2:- Inside the function, create an object of Date Class which allows you to call day, year, month, day, hour, minute, second, etc.

  function currentTime() {     const clock = document.getElementById("time")     const dayIntro=document.getElementById("dayName");      let time = new Date();        // creating object of Date class     let dayName=time.getDay();     let month=time.getMonth();     let year=time.getFullYear();     let date=time.getDate();     let hour = time.getHours();     let min = time.getMinutes();     let sec = time.getSeconds(); }   
Enter fullscreen mode Exit fullscreen mode

Step 3:- The Date object works on the 24-hour format so we change the hour back to 1 when it gets larger than 12. The AM/PM also changes according to that.

  var am_pm = "AM";    if(hour==12)    am_pm = "PM";     if (hour > 12)     {      hour -= 12;      am_pm = "PM";    }    if (hour == 0)     {      hour = 12;      am_pm = "AM";    }   
Enter fullscreen mode Exit fullscreen mode

Step 4:- The obtained hours, minutes, and seconds from Date object will be displayed in single-digit if less than 10. To display the elements of time in two-digit format, a 0 is appended before them whenever they are less than 10.

   hour = hour < 10 ? "0" + hour : hour;  min = min < 10 ? "0" + min : min;  sec = sec < 10 ? "0" + sec : sec;   
Enter fullscreen mode Exit fullscreen mode

Step 5:- Now once our time is ready, make a string using the same HH: MM: SS format changing the hour, minute, and a second value with the values, we get from Date object methods.

  //value of current time let currentTime = hour + ":" + min + ":" + sec +" "+ am_pm;  // value of present day(Day, Month, Year) var months=["January","February","March","April","May","June","July","August","September","October","November","December"]; var week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];  var presentDay=week[dayName]+", "+months[month]+" "+date+", "+year;   
Enter fullscreen mode Exit fullscreen mode

Step 6:- Once the string is ready, let's display it in the div which we made before. This is done by obtaining the div using the document.getElementById method and give our time as the content of the div using the innerHTML property.

  const clock = document.getElementById("time"); const dayIntro=document.getElementById("dayName");  clock.innerHTML = currentTime; dayIntro.innerHTML = presentDay;   
Enter fullscreen mode Exit fullscreen mode

Step 7:- To call the function every second use setInterval() method and set the time-interval as 1000ms which is equal to 1s.(Call setInterval() method outside the function).

  setInterval(currentTime, 1000);   
Enter fullscreen mode Exit fullscreen mode

Step 8:- Call the function currentTime() at the end to start function at exact reloading of page.

  currentTime();  //calling currentTime() function to initiate the process    
Enter fullscreen mode Exit fullscreen mode

Complete javascript code

index.js

  setInterval(currentTime, 1000);  function currentTime() {     let time = new Date();   // creating object of Date class     let dayName=time.getDay();     let month=time.getMonth();     let year=time.getFullYear();     let date=time.getDate();     let hour = time.getHours();     let min = time.getMinutes();     let sec = time.getSeconds();      var am_pm = "AM";     if(hour==12)     am_pm = "PM";     if (hour > 12) {     hour -= 12;     am_pm = "PM";     }     if (hour == 0) {     hour = 12;     am_pm = "AM";     }      hour = hour < 10 ? "0" + hour : hour;     min = min < 10 ? "0" + min : min;     sec = sec < 10 ? "0" + sec : sec;     //value of current time    let currentTime = hour + ":" + min + ":" + sec +" "+ am_pm;    // value of present day(Day, Month, Year)   var months=["January","February","March","April","May","June","July","August","September","October","November","December"];   var week=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];    var presentDay=week[dayName]+", "+months[month]+" "+date+", "+year;    const clock = document.getElementById("time");   const dayIntro=document.getElementById("dayName");    clock.innerHTML = currentTime;   dayIntro.innerHTML = presentDay; }  currentTime();  //calling currentTime() function to initiate the process    
Enter fullscreen mode Exit fullscreen mode

congrats.gif
You have just created a digital clock. It will look something like this!.
Demo

  • Live Demo
  • You can find the code at my GitHub Repository

If you enjoyed learning and find it useful please do like and share so that, it reaches others as well 🤝

Thanks for reading 😃

I would ❤ to connect with you at Twitter | LinkedIn | GitHub

Let me know in the comment section if you have any doubt or feedback.

You should definitely check out my other Blogs:

  • Introduction to JavaScript: Basics
  • Playing with JavaScript Objects
  • 7 JavaScript Data Structures you must know
  • Git & Github: All you need to know
  • Introduction to ReactJS

See you in my next Blog article, Take care!!

Happy Learning😃😃

csshtmljavascriptwebdev
  • 0 0 Answers
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.