Javascript - Simple Digital Clock

In this tutorial we will create a Simple Digital Clock using Javascript. JavaScript is a scripting or programming language that allows you to implement complex things on web pages. It is widely used in designing a stunning website. It is an interpreted programming language that has a capabilities of Object-Oriented. This code can be used to your system that needed a timestamp. So Let's do the coding.

Before we started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the bootstrap that has been used for the layout of the calculator https://getbootstrap.com/.

The Main Interface

This code contains the interface of the application. This code will render application and display a digital clock. To create this just write these block of code inside the text editor and save this as index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
  5. <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
  6. </head>
  7. <nav class="navbar navbar-default">
  8. <div class="container-fluid">
  9. <a class="navbar-brand" href="https://sourcecodester.com">Sourcecodester</a>
  10. </div>
  11. </nav>
  12. <div class="col-md-3"></div>
  13. <div class="col-md-6 well">
  14. <h3 class="text-primary">Javascript - Simple Digital Clock</h3>
  15. <hr style="border-top:1px dottec #ccc;">
  16. <div id="myClockDisplay" style="width:80%; font-size:60px; border:10px solid #000;">
  17. </div>
  18. </center>
  19. </div>
  20.  
  21. </body>
  22. <script src="js/clock.js"></script>
  23. DisplayTime();
  24. </html>

Creating the Script

This code contains the script of the application. This code will render a digital clock that runs base on you computer clock. To do this just copy write the code as shown below inside the text editor and save it as clock.js
  1. function DisplayTime(){
  2. var date = new Date();
  3. var hour = date.getHours();
  4. var minute = date.getMinutes();
  5. var seconds = date.getSeconds();
  6. var day = "AM"
  7.  
  8. if(hour == 0){
  9. hour = 12;
  10. }
  11.  
  12. if(hour > 12){
  13. hour-=12;
  14. day = "PM"
  15. }
  16.  
  17. hour = (hour < 10) ? "0" + hour : hour;
  18. minute = (minute < 10) ? "0" + minute : minute;
  19. seconds = (seconds < 10) ? "0" + seconds : seconds;
  20.  
  21. var currentTime = hour + ":" + minute + ":" + seconds + " " + day;
  22. document.getElementById("myClockDisplay").innerText = currentTime;
  23.  
  24. setInterval(DisplayTime, 1000);
  25. }
There you have it we successfully created a Simple Digital Clock using Javascript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Add new comment