Home > Net >  How to show custom time In dom using new Date() object in JavaScript?
How to show custom time In dom using new Date() object in JavaScript?

Time:02-14

I am a beginner in javascript, what I am trying to do is using new Date() object and show a custom hour, minutes and seconds but in countDown() function I have to pass full date and it starts counting from that date.

My goal is for example I give number 1 as (hour) and then it should start counting down.

I would appreciate it if someone can help me

class Timer {
  constructor(holder) {

    var controller = {
      holder: holder,
      end: null,
      intervalID: 0,
      display: function () {
        var _second = 1000;
        var _minute = _second * 60;
        var _hour = _minute * 60;
        var _day = _hour * 24;

        var msg = "";

        var now = new Date();

        var distance = controller.end - now;
        if (distance < 0) {

          clearInterval(controller.intervalID);
          controller.holder.innerHTML = 'EXPIRED!';

          return;
        }

        var days = Math.floor(distance / _day);
        var hours = Math.floor((distance % _day) / _hour);
        var minutes = Math.floor((distance % _hour) / _minute);
        var seconds = Math.floor((distance % _minute) / _second);
        controller.holder.innerHTML = hours   ' Hours | '   minutes   ' Minutes | '   seconds   ' Seconds ';

      }
    };

    this.countDown = function (end) {
      controller.end = end;
      controller.intervalID = setInterval(controller.display, 1000);
    };
  }
}

var timers = {};

timers.one = new Timer(document.getElementById("one"));
timers.two = new Timer(document.getElementById("two"));
timers.three = new Timer(document.getElementById("three"));


//Hier I should be able to give a number
timers.one.countDown(new Date("Feb 30, 2022 15:37:25"));
timers.two.countDown(new Date(2022, 10, 29, 12, 40, 40));
timers.three.countDown(new Date(2022, 11, 9, 13, 45, 30));
 <div id="one"></div>
 <div id="two"></div>
 <div id="three"></div>

CodePudding user response:

finally, I could manage and find an answer to this question, here we need to convert the time to second and use the getTime() method, for this reason we need to write to function to do this job. In the following you can see the code.

function CreateEndTime(hours, minutes, seconds)
 {
   const result = new Date(new Date().getTime()   ConvertInMilliSeconds(hours, minutes, seconds));
   return result;
 }
 
 function ConvertInMilliSeconds(hours, minutes, seconds)
 {
   const result = (((hours * 60)   minutes) * 60)   seconds;
   return 1000 * result;
 }

  • Related