0

I would like to have a timer where it does something after 12 hours. I would like to begin at 6am and end at 6pm. The time only needs to be for 12 hours. I would like to know how I can adjust the time. What I would like to do is convert my current 12-hour clock into 24 hours.

I'm looking for working examples

The code example is 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);
            }
            //seconds
          }, 0)
      }());
Spanky
  • 699
  • 2
  • 11
  • 38
  • 2
    A `setInterval` with a duration of `0` is going to run a crazy amount of times. – Taplar Nov 24 '20 at 23:12
  • 1
    "So far the time is only set to 8 hours" ... where? add 4 hours to that – Bravo Nov 24 '20 at 23:12
  • Does this answer your question? [How do you display JavaScript datetime in 12 hour AM/PM format?](https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format) – DCR Nov 24 '20 at 23:13
  • @Taplar Any suggestions? – Spanky Nov 24 '20 at 23:16
  • 2
    If you are wanting to actively update a display, and the display goes as granular as displaying seconds, then related your setInterval shouldn't run multiple times within a second. It should run ever second, or `1000` milliseconds – Taplar Nov 24 '20 at 23:17
  • I'd put the node script behind cron – Dominik Nov 24 '20 at 23:17
  • 1
    Probably the constant `second` should be instead of `0` – s.kuznetsov Nov 24 '20 at 23:17
  • If you want the countdown to be seen by all users of the website. You should save your data on the server then every time the page load take the current time and subtract two. Amount of time given represent as you wish and use `setInterval` to count it down further for the viewer. That's what I would do. – Danilo Ivanovic Nov 24 '20 at 23:38
  • @Taplar Ok I changed the setInterval time but now I would like to set my timing for 12 hours – Spanky Nov 24 '20 at 23:45

2 Answers2

0

This should work, it will show the time until 8:00 PM when its 8:00 AM. Here's the pen I made to test it Time Until.

var doIt = false;
var now = new Date();
var seconds;
var date1;
var eight = new Date();
eight.setHours(20, 0, 0);
var date2;
var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

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

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

 }
window.setInterval(function(){
    date2 = new Date();
    if(date2.getHours() >= 8) {
        doIt = true;
    }
}, 1);
window.setInterval(function(){
    date2 = new Date();
    if(date2.getHours() >= 20){
        doIt = false;
    }
}, 1);
window.setInterval(function(){
  if(doIt === true){
    seconds = diff_seconds(new Date(), eight);
    document.querySelector("p").textContent = "It is from 8AM to 8PM";
    document.querySelector("#hours").textContent = toHHMMSS(seconds);
  }
}, 1000)
<p>It is not 8 AM yet</p>
<div id="hours"></div>

Hope it works!

Someone21
  • 91
  • 10
0

I would use Luxon.js:

npm install luxon

Then, it's an easy...

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 );
}

If invoked with

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

const start = DateTime.local().plus({seconds: 15}).toISO();
countdown(start);
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135