0

This is what I have tried. Am getting 21 which is definitely not right. What am I doing wrong?

var today = new Date();
var TrumpsStateVisit = new Date('March 12, 2018 12:00:00');
var daysTillTrumpsStateVisit = TrumpsStateVisit.getTime() - today.getTime();
daysTillTrumpsStateVisit = (daysTillTrumpsStateVisit / 864000000); //number of milleseconds in a day

var $countDownTillTrumpsChinaTrip = ('#countDownTillTrumpsChinaTrip');
$countDownTillTrumpsChinaTrip.textContent = Math.floor(daysTillTrumpsStateVisit);
pigusan
  • 109
  • 9
  • 2
    `86400000` there should be 5 zeroes ;) – ixpl0 Aug 07 '17 at 23:17
  • Probably a duplicate of [*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) – RobG Aug 07 '17 at 23:46

2 Answers2

0

You were so close!

The main problem is that there aren't 864000000 milliseconds in a day, there are only 86400000; you had one zero too many.

A secondary problem occurs with Daylight Savings; not every day has exactly 24 hours in it, so you need to round the result rather than floor it:

var today = new Date();
var TrumpsStateVisit = new Date('March 12, 2018 12:00:00');
var daysTillTrumpsStateVisit = TrumpsStateVisit.getTime() - today.getTime();
daysTillTrumpsStateVisit = (daysTillTrumpsStateVisit / 86400000); //number of milleseconds in a day

console.log(Math.round(daysTillTrumpsStateVisit));

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • There aren't always 24 hrs in a day (where daylight saving is observed), so the result should be rounded, not floored. – RobG Aug 08 '17 at 00:15
  • @RobG -- True, I had forgotten about this; thanks for pointing it out! I've updated my answer to cover this :) – Obsidian Age Aug 08 '17 at 00:23
0

The main reason this doesn't work is that the number of milliseconds in a day is 100*60*60*24=86400000. You also should construct the date differently as that will be March 12, 2018 12:00 in whatever timezone the users browsers in which might not be what you intend.

However there a number of settle issues related to time changes and other issues when subtracting dates so you should really use a library like https://momentjs.com/ that specializes in handling dates and times.