What is the best way to format a time in a 12-hour clock using JavaScript?

Is it possible to create a timer that performs an action after 12 hours? I want the timer to start at 6am and end at 6pm, lasting for exactly 12 hours. Additionally, I'm interested in converting my current 12-hour clock into a 24-hour format.

I am seeking functional examples of this implementation.

You can find the code example in this CodePen link: Timer Link

(function () {
    const second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24;

    let birthday = "Nov 25, 2020 00:00:00",
        countDown = new Date(birthday).getTime(),
        x = setInterval(function() {    
            let now = new Date().getTime(),
                distance = countDown - now;

            document.getElementById("days").innerText = Math.floor(distance / (day)),
            document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
            document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
            document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);

            //do something later when date is reached
            if (distance < 0) {
                let headline = document.getElementById("headline"),
                    countdown = document.getElementById("countdown"),
                    content = document.getElementById("content");

                headline.innerText = "It's my birthday!";
                countdown.style.display = "none";
                content.style.display = "block";

                clearInterval(x);
            }
        }, 0)
}());

Answer №1

If I were to suggest a solution, I'd recommend utilizing Luxon.js library:

npm install luxon

By doing so, you can easily create a countdown timer like the one below:

const {DateTime, Duration} = require('luxon');

function countdown(zeroDate) {
  const zero = DateTime.fromISO(zeroDate);
  const timer = setInterval(function() {
    const delta = zero
                 .diff(DateTime.local())
                 .shiftTo('days', 'hours', 'minutes', 'seconds', 'milliseconds');
    const {days: d, hours: h, minutes: m, seconds: s} = delta;

    if ( delta.valueOf() < 1 ) {
      console.log("Happy Birthday!");
      clearInterval(timer);
    } else {
      console.log(`${d}d ${h}h ${m}m ${s}s Remaining`);
    }

  }, 1000 );
}

To start the countdown, simply use the code snippet below:

const {DateTime, Duration} = require('luxon');

const start = DateTime.local().plus({seconds: 15}).toISO();
countdown(start);

Answer №2

This code is designed to display the time remaining until 8:00 PM when it is currently 8:00 AM. You can view a demo of this code on this page.

var checkTime = false;
var currentTime = new Date();
var secondsRemaining;
var startDate;
var eightPM = new Date();
eightPM.setHours(20, 0, 0);
var endDate;
var formatTime = (secs) => {
    var secNumber = parseInt(secs, 10)
    var hours   = Math.floor(secNumber / 3600)
    var minutes = Math.floor(secNumber / 60) % 60
    var seconds = secNumber % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}
function calculateSeconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  return Math.abs(Math.round(diff));

 }
window.setInterval(function(){
    endDate = new Date();
    if(endDate.getHours() >= 8) {
        checkTime = true;
    }
}, 1);
window.setInterval(function(){
    endDate = new Date();
    if(endDate.getHours() >= 20){
        checkTime = false;
    }
}, 1);
window.setInterval(function(){
  if(checkTime === true){
    secondsRemaining = calculateSeconds(new Date(), eightPM);
    document.querySelector("p").textContent = "It is from 8AM to 8PM";
    document.querySelector("#hours").textContent = formatTime(secondsRemaining);
  }
}, 1000)
<p>It is not yet 8 AM</p>
<div id="hours"></div>

Hoping for successful execution!

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

A function injected into a constructor of a class causes an undefined error

As I delve into learning about utilizing typescript for constructing API's, I have encountered a couple of challenges at the moment. Initially, I have developed a fairly straightforward PostController Class that has the ability to accept a use-case wh ...

Steps to record and upload a video directly to the server using getusermedia

For my application, I need the user to record a video and have it saved on the server disk instead of downloading it to the client browser. I am currently using getusermedia for this purpose, with the following code: (function(exports) { exports.URL = exp ...

JavaScript: A pair of radio button selections

I'm facing an issue with a short form that has two questions and radio buttons for answers. When the first question is answered "No," I used JS code to disable options for the second question, which works fine. However, if the answer is changed back t ...

Serializing intricate objects using JavaScript

I'm curious if there are any options outside of npm for serializing complex JavaScript objects into a string, including functions and regex. I've found a few libraries that can do this, but they all seem to depend on npm. Are there any good seri ...

Passport appears to be experiencing amnesia when it comes to remembering the user

After extensive research online, I have yet to find a solution to my issue. Therefore, I am reaching out here for assistance. I am currently working on implementing sessions with Passport. The registration and login functionalities are functioning properl ...

How to optimize form fields in Bootstrap by utilizing the size/maxlength attributes in HTML inputs

When I attempted to utilize html5's form size/maxlength with bootstrap, I encountered an intriguing issue. The .form-control class in bootstrap overrides the size, but if removed, the input loses its styling. Check out the code pen here: http://code ...

Heroku App Breaks Down - Fails to Render Static HTML Content (Express Server)

Despite my best efforts, I keep encountering this persistent error on Heroku whenever I attempt to serve a static HTML page with some basic JS, images, and CSS. I diligently followed all the advice from SO, made adjustments to index.js, restructured files, ...

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

Determine if an option is chosen in multiple select elements using Vanilla JavaScript

In order to determine if a checkbox is checked, we use the following code: let isChecked = event.target.checked But what about multiple select options like the example below? <select name="books[]" multiple> <option value="A">A</option& ...

Tips for utilizing an adaptive design with Angular

I am working on designing a page that allows for scrolling if needed. On each section of the page, I will be incorporating specific components with unique colors to enhance the layout. However, my current HTML code is not producing the desired result as sh ...

Activate Pop-up for a single instance on BigCommerce

After researching and adding my own code, I am still struggling to get this question answered correctly. Here are the key points I am trying to achieve: 1. Automatically open a popup when the homepage loads. 2. Ensure that the popup is centered on all brow ...

Leveraging jQuery to extract the value from a concealed form field

Seeking assistance with a jQuery issue... I am attempting to use jQuery to retrieve the values of hidden fields in a form. The problem I am facing is that there are multiple forms displayed on the same page (result set items for updating), and the jQuery ...

Tips for concealing JavaScript code while inspecting elements with AngularJS

Is it possible to display minified JavaScript code when using Angular and inspecting elements? ...

Changing the index of an item in an array in React based on order number

Hey there, I'm a new Reactjs developer with a question. It might be simple, but I'm looking to learn the best practice or optimal way to change the index of a selected item in an array based on user input. Essentially, the user will provide a num ...

How can jQuery be used to determine if the number of checked checkboxes is a multiple of three?

Within the ul, I have li tags with checkboxes and I want to create a function that checks, when the submit button is pressed, if the number of checked checkboxes is not a multiple of 3. If it isn't, an alert should be displayed. How can I accomplish t ...

The CSS does not get applied to the returned element in Next JS

When I create a function to return a DOM element with an associated className, the local style doesn't seem to be applied. For example: export default function thing(){ const elem = function(){ return (<div className="myCss">Hello< ...

Unplanned pathways on a node-based server

Building a server, I've utilized the following code snippet: function uniqueString(length) { var result = ''; var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (var i = length; i &g ...

Tips for defining conditions within the style attribute in JSP

Below is the code that I attempted: <div style="width:85%;"> <input class="formbutt" value="AddNew" title="AddNew" type="button" style="{(${projectEnvironmentBean.divStyle}=='dipslay:none') ? 'display:block' :'display: ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...