-5

Whats the best way to calculate the number of days between today and September 12th?

I tried looking for similar questions, but they are asking for the days between 2 fixed dates. My "today" date will be changing every time the page refreshes.

Also in other questions, the "other date" is always set to noon. This will skew my days since my "today" date will not start at noon. It will start at "today" and whatever the time is - not noon.

javedb
  • 228
  • 2
  • 12
  • Today’s date is fixed. – Dave Newton Jun 04 '20 at 13:05
  • You can set the current date with `new Date()` and othe other date is September 12th. The rest you already have searched – Shubham Khatri Jun 04 '20 at 13:05
  • @ShubhamKhatri Yes, but in other questions, they always have the "other date" set to noon. This will skew my days since my "today" date will not start at noon. It will start at "today" and whatever the time is - not noon. – javedb Jun 04 '20 at 13:07
  • convert both dates to utc before comparing – Shubham Khatri Jun 04 '20 at 13:11
  • The time of day doesn’t change what day it is. – Dave Newton Jun 04 '20 at 13:26
  • Does this answer your question? [How do I get the number of days between two dates in JavaScript?](https://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) – Ken Kinder Jun 04 '20 at 13:34
  • Does this answer your question? [Accurately calculate days between two dates (including time)](https://stackoverflow.com/questions/27215173/accurately-calculate-days-between-two-dates-including-time) – Martin Jan 04 '22 at 15:06

1 Answers1

0

Maybe Like this:

var start_time = new Date();
    var end_time = new Date('2020-09-12T00:00:01');
    var timeDiff = end_time - start_time;
    timeDiff /= 1000;
    var seconds = Math.round(timeDiff);

    var h = Math.floor(seconds / 3600);
    var d = Math.floor(h / 24);
    h %= 24;
    seconds %= 3600;
    var m = Math.floor(seconds / 60);
    var s = seconds % 60;

    var elapsed_time = '';

    if(h>0){
     if(h<10){h='0'+h;}
     if(m<10){m='0'+m;}
     if(s<10){s='0'+s;}
     elapsed_time = h + ':' + m + ':' + s;
    }else if(m>0){
     if(m<10){m='0'+m;}
     if(s<10){s='0'+s;}
     elapsed_time =  m + ':' + s;
    }else if(s>0){
     if(s<10){s='0'+s;}
     elapsed_time =  s +' sec.';
    }
    if(d>0){
     elapsed_time = d+' days and ' +elapsed_time;
    }
    console.log('elapsed days -> ' +d);
    console.log('full format -> ' +elapsed_time);
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17