Take away the seconds from a timepiece

I've been searching for a solution to this problem without much success. Essentially, I have a clock displayed in a 12-hour format that automatically appears when the page loads. My goal is to switch the clock format to 24 hours using an AddEventListener. Additionally, I would also like to implement another AddEventListener to remove the seconds display. Below is the code snippet I'm currently working with:

function myClock() {
  let date = new Date(); 
  let hh = date.getHours();
  let mm = date.getMinutes();
  let ss = date.getSeconds();
  let session = "AM";

  if(hh == 0){
      hh = 12;
  }
  if(hh > 12){
      hh = hh - 12;
      session = "PM";
   }

   hh = (hh < 10) ? "0" + hh : hh;
   mm = (mm < 10) ? "0" + mm : mm;
   ss = (ss < 10) ? "0" + ss : ss;
   
   let time = hh + ":" + mm + ":" + ss + " " + session;

  document.getElementById("time-now").innerText = time; 
  var t = setTimeout(function(){myClock()}, 1000); 
 
}
myClock();
<span id="time-now"></span>

Answer №1

In this snippet, the logic has been condensed and includes thorough testing of edge cases by utilizing the .toLocaleTimeString() method. This method allows you to set a specific locale and customize the formatting, such as using a 24-hour clock.

function displayClock(locale) {
  const currentDate = new Date(); 
  const currentTime = currentDate.toLocaleTimeString(locale, { hour12: false })
  document.getElementById("current-time").innerText = currentTime; 
  setTimeout(() => displayClock(locale), 1000); 
}
// Example with United States locale
displayClock('en-US');
<span id="current-time"></span>

Answer №2

function displayTime(locale) {
  const currentDate = new Date();
  const currentTime = currentDate.toLocaleTimeString(locale, { hour12: false });
  document.getElementById("current-time").innerText = currentTime;
  setTimeout(() => displayTime(locale), 1000);
}
// Display time in US format as an example
displayTime('en-US');

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

What is the best way to transfer data between different states in ReactJS components?

I am in the process of developing an application that will showcase a list of categories. Upon selecting a category, the application will transition to the next page where a query regarding water type will be posed. Once the water type is chosen, the app s ...

How to successfully embed a podcast episode into an MHT file

I have received an MHT file from Adobe Contribute that contains a flash file for a podcast. The player is supposed to display and then pull the mp3 file, but it seems to be more complex than just a single file. <script type="text/javascript" src="swfob ...

Unable to maintain active status on Vuejs (PrimeVue) Sidebar component leads to malfunction

I currently have a PrimeVue Sidebar component set up with a dynamic component being passed to it. At the moment, I am only using a single component to test this functionality. <Sidebar v-model:visible="sidebarState" :baseZIndex="1000" ...

The challenge of harmonizing variables in PHP and JavaScript

I have a PHP script that generates an HTML table displaying data from a MySQL database. <?php include 'connexion.php'; session_start(); $idfirm = $_REQUEST['idfirm']; $namefirm = $_REQUEST['namefirm']; The table rows are ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Troubleshooting your Meteor App on Nitrous.io with server-side debugging

I currently have a basic Meteor application up and running on a Nitrous box. I am interested in utilizing node-inspector for debugging the server-side part of my app, but I'm facing difficulty accessing the console as detailed here. The Meteor app is ...

Create a JavaScript onclick popup that hides the destination URL without displaying it

After searching through numerous forums without finding a satisfactory answer, I decided to turn to Stackoverflow for help. Unsure if this is the right category for my question. I'm looking to hide an href link that opens as a popup. It's diffic ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Exploring the impact of nested if statements on the incrementation of a for loop

I'm trying to understand the logic behind this FCC activity. I'm puzzled as to why the code is using keys.length instead of collection.length to iterate over the Array of objects. In this example, keys.length is only 1 while the collection array ...

Tips for calculating the total of unchecked checkboxes and an array checkbox using javascript

I've been attempting to calculate the total sum of values from dynamically selected checkboxes, such as "uniform", "educfees", and schoolFees, in addition to other checkboxes stored in an array (e.g., fees). However, this task has proven challenging, ...

Extract content from whole webpage including HTML, CSS, and JavaScript

Currently I am working on developing a webpage version control backup/log system. The goal is to automatically save a static copy of the webpage, including all its CSS and JavaScript files, whenever there are any changes made. I have already figured out h ...

"Explore the convenience of viewing two separate videos on one webpage, each in its own

After extensive research, I have been unable to find any information on the issue at hand. I am attempting to use the jquery plugin OkVideo to display different videos in two separate "section" tags. However, even after explicitly assigning IDs to each con ...

What is the best way to retrieve the Firebase API key from an Express backend in order to initialize firebase.initializeApp()?

At the moment, my Firebase.js file is structured to fetch the API key from the .env file on the client side. Here's a snippet of the code: import firebase from "firebase/compat/app"; import "firebase/compat/auth"; import "firebase/compat/firestore" ...

Leverage JavaScript to add the rel=0 attribute to a specific URL

Currently, I am integrating videos into my WordPress website using a plugin and I'm looking for a way to ensure that all the YouTube URLs contain rel=0 to eliminate related videos at the end. Can anyone suggest the best approach to achieve this? Any ...

A guide to effectively converting and parsing a class object that includes Uint8Array elements

After stringifying a class object that contains a property in Uint8Array, and then parsing it later, the property is no longer in Uint8Array format. Here's an example: class Example { title:string; byteData:Uint8Array; ...

How can I loop through SVG elements and attach an event listener to each one in JavaScript?

I am struggling with loading a simple SVG file and iterating through the shape nodes to add an onclick event. Unfortunately, after the SVG file is loaded, it cannot find the shape nodes. What could be the issue here? Here is the SVG code snippet: < ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

Using ThreeJS in conjunction with NextJS requires that class constructors be called with the 'new' keyword

Seeking assistance with rendering a basic scene within a nextJS route named "lab2". Encountering the following error: Error: class constructors must be invoked with 'new' Call Stack: renderWithHooks mountIndeterminateComponent ...

Utilizing Animated GIFs as Textures in THREE.js

I'm trying to figure out how to incorporate a GIF animation as a texture in THREE.js. While I can successfully load a texture (even in GIF format), the animation doesn't play. Is there a solution to this? I came across some resources like these: ...