1
    const yearTxt = document.getElementById( "years" );
    const monthTxt = document.getElementById( "months" );
    const daysTxt = document.getElementById( "days" );
    const hoursTxt = document.getElementById( "hours" );
    const minutesTxt = document.getElementById( "minutes" );
    const secondsTxt = document.getElementById( "seconds" );
    
    const countDown = () => {
      let current = new Date();
      let dateOfPotentialDeath = new Date( "2077-05-13T08:05:00.000Z" );
      dateOfPotentialDeath.setFullYear( "2077" );
      let rest;
      const totalSeconds = ( dateOfPotentialDeath.getTime() - current.getTime() ) / 1000;
      const years = Math.floor( totalSeconds / 31_536_000 );
      rest = ( totalSeconds / 31536000 ) - years;
      const months = Math.floor( ( rest * 31_536_000 ) / 2_628_288 );
      rest = ( ( rest * 31_536_000 ) / 2_628_288 ) - months;
      const days = Math.floor( ( rest * 2_628_288 ) / 86400 );
      rest = ( ( rest * 2_628_288 ) / 86400 ) - days;
      const hours = Math.floor( ( rest * 24 ) );
      rest = ( rest * 24 ) - hours;
      const minutes = Math.floor( rest * 60 );
      rest = ( rest * 60 ) - minutes;
      const seconds = Math.floor( rest * 60 );
      console.log( years, months, days, rest, hours );

Is there any easier way to do this part above.I tried subtracting two dates but it gives me wrong year.I have tried this

      new Date(date1 - date2);

But it gives me 2024 i know it isn't posible to have date before 1970 but is there any other way this could be done?

      secondsTxt.innerText = seconds;
      minutesTxt.innerText = minutes;
      hoursTxt.innerText = hours;
      daysTxt.innerText = days;
      monthTxt.innerText = months;
      yearTxt.innerText = years;

    
      // const days = Math.floor(seconds / 3600 / 60)
      // const hours = Math.floor(seconds/3600)
    };
    
    setInterval( countDown, 1000 );
Darko
  • 11
  • 1
  • WHAT are you trying to do? Get the time difference between two dates? Unclear why you would use Date constructor with the difference. – epascarello Jul 18 '22 at 16:20
  • This might be better asked on https://codereview.stackexchange.com/? – evolutionxbox Jul 18 '22 at 16:21
  • https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript – epascarello Jul 18 '22 at 16:22
  • or https://stackoverflow.com/a/27187801/294949 – danh Jul 18 '22 at 16:22
  • Does this answer your question? [How do I get the difference between two Dates in JavaScript?](https://stackoverflow.com/questions/41948/how-do-i-get-the-difference-between-two-dates-in-javascript) – James Jul 18 '22 at 16:24

0 Answers0