2

Okay - I am still very new to JavaScript, please be understanding and patient with me.

I have a script that returns two dates: one from a text file and the other is the system date. These two dates are displayed in this format:

Tue 29 Jun, 12:57 PM (from the text file) and 
Mon Jul 26 2021, 11:47:21 PM (from the system date).

When I tried to subtract the two dates, I get this for output on the console:

NaN

I used the following code to try to get the difference between the two dates:

const diffInMilliseconds = Math.abs('computer_date' - 'slug_date');
console.log(diffInMilliseconds);

What does NaN mean? What is the correct way to get the difference of two dates in JavaScript? Do I need to convert the dates to another format before subtracting them?

***** Update ******

I am inserting the code that I have put together for trying to parse the date from a text file and compare to the system date.

const fs = require('fs');
//var str;
var slug_date = " ";
var computer_date = " ";
var diffInMinutes = 0;
fs.readFile('/home/xxxx/xxxx/xxxx/ocrtextparse.txt', 'utf8', function (err, data) {
  var targetStr = 'Last Update:';
  //var slug = targetStr.split(': ').pop(); // 2020
  //var slug = targetStr.substring(targetStr.indexOf(':') + 1); // 01-2020
  if (err) throw err;
  if(data.includes(targetStr)){
   console.log(data)
   console.log(targetStr + " is present" + "\n")
   //console.log(slug)
  }

  let arr = data.split(/\r?\n/);
  arr.forEach((line, idx)=> {
      if(line.includes(targetStr)){
      console.log("Line " +(idx+1)+') '+ line + "\n");
      //console.log(line.substring(line.indexOf(':')+ 2))
      var slug = line.substring(line.indexOf(':')+ 2);
      //console.log(slug)
      slug_date = slug;
      //console.log(slug_date)
      }
  })
  
  //console.log(slug_date);

  // get a new date (locale machine date time)
  var date = new Date();
  // get the date as a string
  var n = date.toDateString();
  // get the time as a string
  var time = date.toLocaleTimeString();

  // log the date in the browser console
  //console.log('date:', n);
  // log the time in the browser console
  //console.log('time:',time);
  computer_date = (n + ", " + time);
  //console.log(n + ", " + time);
  console.log(computer_date);
  console.log(slug_date);
  //console.log("\n");
  
  var file_date = Date.parse(slug_date);
  //const diffInMilliseconds = Math.abs(computer_date - file_date);
  //console.log(diffInMilliseconds);
  console.log("\n");

  //var date1 = new Date(slug_date);
  var date2 = new Date(Date.now());
  //var date3 = computer_date;
  
  //diffInMinutes = Math.abs(Number(date2.getTime()) - Number(date1.getTime()))/60000;

  //console.log(date1)
  console.log(date2)
  //console.log(date3)
  //console.log(diffInMinutes)

  var textFileDate = ((slug_date));
  var appendYear = textFileDate.replace(',', ' ' + new Date().getFullYear()+',');
  //var textFileDate = Date(appendYear);
  console.log(computer_date);
  console.log(appendYear);

  diffInMinutes = Math.abs(Number(date2) - Number(appendYear))/60000;
  console.log(diffInMinutes);
  console.log(Number(date2));
  console.log(Number(appendYear));

 var a = new Date(appendYear);
 var current = Date.now();
 var diff = Math.abs(current - a);

 var minutes = Math.floor((diff/1000)/60)
 console.log("********")
 console.log(minutes);

 console.log("++++++++++++");
 var dateZ = 'Tue 29 Jun, 12:57:00 PM';
 console.log(dateZ);

});

I also have the text file that I am trying to . How can I attach it to my question?

ironmantis7x
  • 807
  • 2
  • 23
  • 58
  • NaN usually means incompatibility. – foundling Jul 27 '21 at 04:00
  • Do you have date variables computer_date and slug_date? You may just need to remove the quotes. Its calculating subtraction on two strings, which is NaN. – Paul Rooney Jul 27 '21 at 04:45
  • As a general rule, don't mix `var` (old Javascript) with `let`/`const` (new Javascript, ES6/ECMAScript2015). You might want to look into using a library like [moment.js](https://momentjs.com/) for parsing and displaying time, as the build-in date functions are somewhat limited. – Codebling Aug 03 '21 at 17:16

4 Answers4

2

You have quotes around your values. The quotes tell Javascript to interpret the data in the quote as a string. You are trying to subtract two strings, like "oranges" - "apples". Javascript doesn't understand this, which is why you are getting NaN.

NaN stands for Not a Number, and is what you get when you try to do something mathy that cannot you, such as divide by zero, or subtract things that can't be subtracted.

To fix it, remove the quotes:

const diffInMilliseconds = Math.abs(computer_date - slug_date);
Codebling
  • 10,764
  • 2
  • 38
  • 66
1

The simplest would be to use Date.parse():

var origin_unix = Date.parse('Tue 29 Jun, 12:57 PM');
var current_unix = Date.now();

console.log( "Difference in Milliseconds: " + (current_unix - origin_unix) );

You may want to double-check that date from the text file, though, as there is no year.

matigo
  • 1,321
  • 1
  • 6
  • 16
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Safari parses 'Tue 29 Jun, 12:57 PM' as 2000, Chrome as 2001, Firefox as an invalid date. – RobG Jul 27 '21 at 08:59
  • yes not having a year seems to really monkey wrench the whole thing. Also @matigo: the date string from the text file seems to be an issue as well. i cannot convert it to a date at all.... – ironmantis7x Aug 01 '21 at 04:27
1

First substract two dates using Math.abs() gives you the result in milliseconds. dividing the result by 1000 gives you the seconds, divide that by 60 gives you the number of minutes.

var a = new Date('Tue 29 june 2021, 12:57 PM')
var current = Date.now();
var diff = Math.abs(current - a);

var minutes = Math.floor((diff/1000)/60)
console.log(minutes);
Bhanu Pratap
  • 144
  • 6
1

Try this,

NaN stands for "Not a Number", if you try to perform mathematical operations on the data type other than number, you generally see this error.

text file refers to the year 2001, see the output below

var date1 = new Date('Tue 29 Jun, 12:57 PM');
var date2 = new Date(Date.now());
diffInMinutes = Math.abs(Number(date1.getTime()) - Number(date2.getTime()))/60000;


//output
10559347.2098
date1
Fri Jun 29 2001 12:57:00 GMT+0530 (India Standard Time)
date2
Tue Jul 27 2021 10:04:12 GMT+0530 (India Standard Time)


// If you are referring the date to 2021 from the text file, try this

var textFileDate = 'Tue 29 Jun, 12:57 PM';
var appendYear = textFileDate.replace(',', ' ' + new Date().getFullYear()+',');
var textFileDate = new Date(appendYear);
var sysDate = new Date(Date.now());
diffInMinutes = Math.abs(Number(textFileDate.getTime()) - Number(sysDate.getTime()))/60000;

//output

    40164.49135
    textFileDate
    Tue Jun 29 2021 12:57:00 GMT+0530 (India Standard Time)
    sysDate
    Tue Jul 27 2021 10:21:29 GMT+0530 (India Standard Time)
  • See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Safari parses 'Tue 29 Jun, 12:57 PM' as 2000, Chrome as 2001, Firefox as an invalid date. – RobG Jul 27 '21 at 09:04
  • The issue I am having is that the date I pull from the text file is a string. When I call "var date1 = new Date(file_date_variable)" it tells me invalid date. The image I am taking the text from and storing to a file always puts it in the format of (example): "Tue 29 Jun, 12:57 PM‏". How do I get my string variable into the correct format for this work right. – ironmantis7x Jul 27 '21 at 22:56
  • I have successfully added the year but there is something about the date pulled from the text file that still give an invalid date or NaN value when I try to process and work with it. so far everything suggested in the thread doesn't work. I am missing something here and need help understanding – ironmantis7x Aug 01 '21 at 04:29
  • can you copy the date exact date returned from the text file here – priston lewis Aug 02 '21 at 04:05
  • This answer was the closest the answer. Thanks all for your help and input. Turns out the date I scanned from the text file had a format issue. It should be month-day-year. My date in the text file was day-month-year (after adding the year) and that was a format that the system could process. I kept overlooking this small detail. Finally I saw it. So this answer is the closest to helping me fix the problem. – ironmantis7x Aug 03 '21 at 01:47