How to make a Clock with Javascript

Publication: 3 of March, 2020
In this post will go to learn how to make a clock with JavaScript, it will be a project that at the end we can watch on localhost on your computer, but we are going to start for what you guys have come for.
We start by creating a directory with the name of Clock, and we will created inside the User folde of your computer or C:. Now I imagine that you have code editor like Atom, Brackets, and if you don´t have any of these softwares, I encourage you to download it, or you can use the old and friendly Notepad, I mean come on, it was the first place where I wrote my first code.
Now that we have open the text editor our first task will be to create the html file so we can see the clock on the browser, so we type this.

<!DOCTPYE html> 

  <html>    

  <head>   
     
      <title>Hello</title>   
 
      <link rel="stylesheet" type="text/css" href="style.css"> 

  </head>
 
  <body>

    <h1 id="clock"></h1>  

  </body>  
 
    <script src="index.js" type="text/javascript"></script>

  </html>

Notice that we start normally with the, then open the html tag, and normally inside the html tag we create the head and body tag, now inside the head tag, we create the title tag and beneath the title we create the link to our css file so the number can look cool and all of that, then inside the public tag we create the H1 tag with the id of clock and finally outside the body tag we create our script tag so we can link the JavaScript file. Now we save the file inside the Clock directory that we created at the beginning under the name of index.html.
Now that we have completed the first part let´s tackle the JavaScript part, we open the text editor again and now is whe the fun begins.
We start by creating the variable text and that variable will be equal to the id of the H1 tag that we created on the HTML file, so once we get the number for the clock we can display the values in the headline tag, and looks like this


var text = document.getElementById("clock");


Now that we have created the text variable we are going to create the method setInterval, this method will help us to call a function or evaluate an expression at specified intervals set in milliseconds that looks like this


setInterval(function() {}, );


But you will ask; where are the milliseconds?, take easy champ, we are advancing one step at the time, anyhow, let´s continue inside we create a variable with the name of date and will be equal to a new date object.


var date = new Date();


This will retrieve the date in the format as follows Thu Nov 28 2019 16:29:01 GMT-0500 (Eastern Standard Time , but we don´t want show that on our clock, so what are we going to do is get the hours, minutes and seconds of the date, by doing this.

var hours = date.getHours(); 

var minute = date.getMinutes();

var seconds = date.getSeconds();

If you look, we created three variables, that will hold the info need it, that you can see on the values names, so on each variable you will see that we used other date methods, so on the variable hours we are going to get the hours of the date with .getHours(); , look that we don´t use new because the date is on the variable date. and we do the same on minutes and seconds.
Now we are going to create an if statement to know when it has to be applied the PM and AM format, when we got the date at the beginning with the variable of the same name, it retrieves the hours in 24 instead of 12 like we want to, so we are going to if the hours specified with the variable of the same name are less than 11 if so we create a variable with the value PM and we subtract 12 for the variable hours, and if is more that 11 we set the value of the variable format to AM

if (hours > 11){

    var format = "PM";      

    hours -= 12; 

 } else {    

    format ="AM";

} 

Now so far we have retrieve all the information that we need, but how do we display it on the browser?, by doing this.


text.innerHTML = (`${hours} : ${minute} : ${seconds} ${format}`);


the text variable that we did at the beginning will equal to the time set, I have use template literals because for me because it keeps the code clean, and inside each of them will equal to the variables that hold the information of the hours, minutes, etc, but are missing something very important, set the interval so it can run the function each second, so we add 1000 (milliseconds), between the ending parenthesis and the ending curly bracket of our setInterval()


}, 1000);


And your code should look like this


//get the element h1 to display the clock
    var text = document.getElementById("clock");

//set up setInterval to run the fucntion every second
    setInterval(function() {    

//get today´s date
   var date = new Date();    

   var hours = date.getHours();    

   var minute = date.getMinutes();    

   var seconds = date.getSeconds();

/*the if statemnet to check if is later that 11am so we can change the clock to a 12 hours clock an add PM, AM*/      
  if (hours > 11){   

//set up a variable with the PM value
    var format = "PM";    

//if you want a clock of 24 hours just delete this line
    hours -= 12;    

} else {

//if is earlier that 11 (am) 
     format = "AM";

}   

    text.innerHTML = (`${hours} : ${minute} : ${seconds} ${format}`);

}, 1000);


And if you want to add style, add this to your css file.

@import url('https://fonts.googleapis.com/css?family=Alata&display=swap');
h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;   
    width: 100%; 
    font-family: Alata;
    font-size: 4em;
}

Thank you for reading this post I hope that it was helpful, and I wish all the best.

Copyright Luis Gonzalez 2021