-4

I have to create a function that calculates the time in seconds from now to July 4th.

This is what I have so far:

function getTimeDiff(fdate, pdate) {
  var fSeconds = fdate.getTime();
  var pSeconds = pdate.getTime();
  var secondsLeft = (fSeconds - pSeconds) / 1000
  return secondsLeft;
}

var x = getTimeDiff(new Date(2019, 6, 4, 0, 0), new Date());
console.log(x);

When I run the code in my browser it states that

"fdate.getTime() is not a function"

How do I fix this?

Vikash Pathak
  • 3,444
  • 1
  • 18
  • 32
  • 1
    Possible duplicate of [How Many Seconds Between Two Dates?](https://stackoverflow.com/questions/2024198/how-many-seconds-between-two-dates) – Erik Philips Jun 07 '19 at 04:24
  • 1
    Well, if you want to enter dates... enter dates. `getTimeDiff(new Date(2019, 07, 04, 24, 00, 00), new Date(2019, 06, 07, 24, 11, 00))` – virgiliogm Jun 07 '19 at 04:26

2 Answers2

0

How do I enter dates so that my function recognizes that I am entering a "new Date()"?

Perhaps you mean to do this:

var x = getTimeDiff(new Date(2019, 7, 4, 24, 0, 0), new Date(2019, 6, 7, 24, 11, 0));
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
0

If you want to compare a date to today, there is no need to pass today as a variable to the function (the code will get a little bit simple).

function getTimeDiff(year, month, day) {
  var today = new Date();
  var targetDate = new Date(year, month, day);
  return Math.round( (targetDate.getTime() - today.getTime()) / 1000);
}

console.log(getTimeDiff(2019,6,6));

Because getTime outputs the value in miliseconds, I have divided by 1000 and rounded the value, so you get an integer.

The code outputs somethink like 2293103 (tested in Chrome and Firefox)

Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27