0

I have that function:

function CompareDate() {
    var timeNow = '03.04.2019';
    var timeNowSplit = timeNow.split('.');
    var timeTarget = '04.04.2019';
    var timeTargetSplit = timeTarget.split('.');

    var timeNowObj = new Date(timeNowSplit[2], timeNowSplit[1], timeNowSplit[0]).toUTCString();
    var timeTargetObj = new Date(timeTargetSplit[2], timeTargetSplit[1], timeTargetSplit[0]).toUTCString();

    difference = timeTargetObj - timeNowObj;
    console.log(difference)
}

If i'm launching this inside a node.js console i'm getting just:

"C:\Program Files\nodejs\node.exe" C:\Users\s.manns.WebStorm2018.3\config\scratches\scratch.js NaN

That solution i found on How to calculate date difference in javascript

But why this code just returns a "NaN"?

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
Sascha Manns
  • 2,331
  • 2
  • 14
  • 21
  • 1
    Remove the `.toUTCString()` bit from both and just subtract the date objects – adiga Apr 03 '19 at 09:41
  • ...and Month is `monthIndex` - Integer value representing the month, beginning with `0` for January to `11` for December. :) – Eddie Apr 03 '19 at 09:42

3 Answers3

1

The reason is because you are attempting to calculate the difference of two strings. Remove the toUTCString() from both and it will result in a valid response. For completeness, please note the response you receive will be in milliseconds!

var timeNow = '03.04.2019';
    var timeNowSplit = timeNow.split('.');
    var timeTarget = '04.04.2019';
    var timeTargetSplit = timeTarget.split('.');

    var timeNowObj = new Date(timeNowSplit[2], timeNowSplit[1]-1, timeNowSplit[0]);
    var timeTargetObj = new Date(timeTargetSplit[2], timeTargetSplit[1]-1, timeTargetSplit[0]);

    difference = timeTargetObj - timeNowObj;
    console.log(difference);
DKyleo
  • 806
  • 8
  • 11
0

The method you are using Data.prototype.toUTCString() which changes the date object to UTC equivalent string. Try removing the method and then subtract.

Pranay Tripathi
  • 1,614
  • 1
  • 16
  • 24
0

This should work for you -

function CompareDate() {
    var timeNow = '03.04.2019';
    var timeNowSplit = timeNow.split('.');
    var timeTarget = '04.04.2019';
    var timeTargetSplit = timeTarget.split('.');

    var timeNowObj = new Date(timeNowSplit[2], timeNowSplit[1], timeNowSplit[0]);
    var timeTargetObj = new Date(timeTargetSplit[2], timeTargetSplit[1], timeTargetSplit[0]);

    difference = timeTargetObj - timeNowObj;
    console.log(difference)
}
CompareDate();
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281