Exploring the Benefits of 'new Date()' Function and Adding Leading Zeros to Numbers Less than 10 in a Digital Clock Implemented in JavaScript

As I continue on my journey of learning JavaScript, I challenge myself by building small projects.

Today, I managed to create a digital clock, with a little help from a tutorial.

There are two specific things that I am struggling to grasp, which were not explained in the tutorial. In case anyone is interested, you can find the tutorial here.

Here's the JavaScript code:

setInterval(function() {
  let hours = document.querySelector('.hours');
  let minutes = document.querySelector('.minutes');
  let seconds = document.querySelector('.seconds');

  let h = new Date().getHours();
  let m = new Date().getMinutes();
  let s = new Date().getSeconds();

  hours.innerHTML = h < 10 ? '0' + h : h;
  minutes.innerHTML = m < 10 ? '0' + m : m;
  seconds.innerHTML = s < 10 ? '0' + s : s;

}, 1000);

Issue #1:

I'm unsure about the usage of new Date(). As a beginner exploring objects, I attempted using just getHours(), but it didn't yield the expected result. What am I missing?

Issue #2:

Following the tutorial, if the time was below 10 for hours, minutes, or seconds, they appeared as single digits instead of padded with a zero. I tried implementing some logic like this:

if(m < 10) {
    '0' + s
}

Additionally, I experimented with:

if(m < 10) {
    s = '0' + s;
    return s;
}

However, my attempts were unsuccessful. After reading through the comments, I found a shorthand solution to prepend zeros when necessary, but I am confused about the syntax used, particularly the inclusion of :h, :m, and :s at the end of each statement.

Here's the snippet:

setInterval(function() {
  let hours = document.querySelector('.hours');
  let minutes = document.querySelector('.minutes');
  let seconds = document.querySelector('.seconds');

  let h = new Date().getHours();
  let m = new Date().getMinutes();
  let s = new Date().getSeconds();

  hours.innerHTML = h < 10 ? '0' + h : h;
  minutes.innerHTML = m < 10 ? '0' + m : m;
  seconds.innerHTML = s < 10 ? '0' + s : s;

}, 1000);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
}

.container {
  width: 90vw;
  margin: auto;
  border: 1px solid rgb(50,50,50);
  margin-top: 50vh;
  transform: translateY(-50%);
  display: flex;
  justify-content: space-around;
  padding: .5em;
  font-size: 3em;
  font-family: verdana;
  background: rgb(170,190,170);
  box-shadow: 0 0 10px black inset;
  box-reflect: below 0 linear-gradient(transparent, white);
  -webkit-box-reflect: below 0 linear-gradient(transparent, rgba(255,255,255,.5));
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0>
  <link rel="stylesheet" href="style.css>
  <title>Digital Clock>
</head>
<body>
  
  <div class="container>
    <div class="hours></div>
    <div class="minutes></div>
    <div class="seconds></div>
  </div>

  <script src="main.js></script>
</body>
</html>

Answer №1

Your result includes a conditional (ternary) operator ?: which comprises of three components:

condition ? valueTrue : valueFalse
  • The condition is an expression that can be either truthy, such as true, any non-empty string, any number other than 0 or NaN, objects, functions, or falsy values like undefined, null, '', or zero.

  • valueTrue represents the expression returned when the condition is truthy.

  • valueFalse indicates the expression returned when the condition is falsy.

While this inline condition may seem convenient, it is not recommended to use if the return value is irrelevant.

To achieve a more concise approach, consider converting the value to a string and padding it with zeros at the beginning. For repetitive usage, implement a function for this purpose.

If you need to obtain a Date instance, fetch it once and utilize it to retrieve all time components.

function padZero(value) {
    return value.toString().padStart(2, '0');
}

setInterval(function() {
    let hours = document.querySelector('.hours'),
        minutes = document.querySelector('.minutes'),
        seconds = document.querySelector('.seconds'),
        today = new Date();

    hours.innerHTML = padZero(today.getHours());
    minutes.innerHTML = padZero(today.getMinutes());
    seconds.innerHTML = padZero(today.getSeconds());
}, 200);
<span class="hours"></span>:<span class="minutes"></span>:<span class="seconds"></span>

Answer №2

Small point number 1:

  • What is the reason for using new Date()? The date object must be created in order to obtain the current date and time. The function ( getHours() ) will then extract the hours from this newly created date.

Small point number 2:

  • Why are there :h, :m, :s at the end of each statement? This serves as the format for how this shorthand notation is structured.
STATEMENT ? IF_TRUE : IF_FALSE

Explanation: link

For instance, h<10?'0'+h:h indicates that if h < 10, the innerHTML should be set to '0' + h. If h is greater than or equal to 10, then innerHTML should be h.

if(m < 10) {
 s= '0' + s
 return s
}

This error occurred due to the condition used in the if statement. The variable being checked is 'm', which contrasts with what was explained in the tutorial where it should have been 's' in this scenario.

I hope this provides further clarification :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on closing a React Navigation modal containing multiple screens

I've been using https://reactnavigation.org/ for handling navigation within a React Native application. My setup includes a tab navigator as the main stack and a modal with two screens inside (one for logging in and one for app configuration). I&apos ...

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

Encountering difficulties while attempting to import a module in Next.js

My attempt to import the Zoom Web SDK module into my Next.js project encountered an error due to the undefined window object. Simply trying to import the websdk module resulted in this unexpected issue https://i.stack.imgur.com/NDRoC.png I am using Next ...

What is the best way to incorporate an HTML element using JavaScript?

My attempt to generate a chip when a checkbox is checked by adding an event listener function to the checkbox seems to be failing. It appears that the element is not being inserted into the HTML. Below is the code snippet: let ChoosenFiltercontainer = docu ...

What is the best method to shift an element to the top by a fraction of its height, namely -100%?

I am facing an issue with an element where I set top: -100%. My requirement is to translate top: -100% to top: -{height-of-the-element}. Unfortunately, instead of getting top: -{height-of-the-element}, I am getting top: -{height-of-another-element-wrapping ...

Change the Vue3 PrimeVue theme or CSS file with a simple click or upon page load

One way to incorporate themes is by importing them in the main.js file at the root of the app: import 'primevue/resources/themes/arya-orange/theme.css'; However, I am exploring ways to dynamically switch CSS files based on the user's system ...

Utilizing react.js and passing props as parameters in recursive functions

When using recursion, I encountered an issue where I am unable to pass the props parameter: class App extends React.Component { constructor(props) { super(props); this.state = { visible: this.props.root, a:this.props.a }; } toggle(){ thi ...

Activate Form Submission from Child Component Using Parent Button in React

Looking to achieve Form submission from a Child Component through a button within the Parent component, which is a Slide with a Next Button. The Child Component is displayed on one page of the Slide. The goal is: When the Next Button on the Parent compone ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Once the maximum total of all input fields has been reached, prevent any further input in the remaining

I run an online store where I offer a box of assorted flavor bagels with a maximum of 12 flavors per box. Each flavor has its own number input field, as seen in the screenshot linked below. https://i.sstatic.net/eSU09.png While I have successfully used J ...

After making an Ajax call, jQuery fails to function correctly when the response is displayed in a new pop-up window

Hello there, I'm currently facing an issue with a JSP page that contains a form along with some jQuery code. Everything works perfectly fine until I try to load this page in a popup window using AJAX call, which causes the jQuery code to stop function ...

Turn off the ability for items in Isotope to be set to an absolute

Currently, I am customizing my portfolio and looking to implement my own method for positioning the portfolio items. The Isotope library typically uses absolute positioning with left and top properties to position portfolio elements. Even after trying to o ...

Cease the automatic redirection of the contact form

Hey there, I'm currently working with this contact form: HTML <form action="mail.php" method="POST"> <p>Team Name</p> <input type="text" name="name"> <p>Your Email</p> <input type="text" name="email"> <p& ...

The division is now appearing below the preceding division instead of following it

I am currently encountering an issue that I believe has a simple solution, but I am unable to find it. I have two divs in my code. The first div contains a blurred background image and content, which is working perfectly fine. However, the second div is n ...

The categorization of items into arrays according to selections made with radio buttons is producing varied outcomes

I currently have two groups of radio buttons: One for attendance with values "yes" and "no" Another for dietary choices with values "Vegetarian / Vegan" and "Non-vegetarian" The dietary fields are only displayed if the user selects "yes" for attendance. ...

Ensuring validation for a single checked checkbox in AngularJS

I'm currently experiencing a challenge with checkboxes in my Angular project. Due to the requirements of the backend, each checkbox must have a unique name, but at least one of them needs to be checked before the form can be submitted. To address thi ...

What is the best way to show a specific range of months in the primeng calendar (p-calendar)?

Struggling to showcase a timeframe spanning two months in p-calendar, but without any luck. For instance, I aim to exhibit dates only between the mid of one month and the mid of the following month. I prefer accomplishing this using reactiveForm with fo ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...