Home > Back-end >  Comparing 2 dates in Node.js
Comparing 2 dates in Node.js

Time:08-02

I am trying to make a trial system in Node.js. In my mongoose schema, I put a Date.now which returns 2022-07-31T21:59:27.324 00:00

Then, using Date.now, how would I see if the current date is X days past the saved date?

CodePudding user response:

You can subtract the dates to get the difference in milliseconds

let date1 = new Date("2022-07-31T21:59:27.324 00:00")
let date2 = new Date("2022-08-26T21:59:27.324 00:00")
let differenceInDays = (date2 - date1)/(1000 * 60 * 60 * 24)

CodePudding user response:

Do you want the difference in whole days (e.g., the number of date boundaries crossed between the two points in time), or do you want the number of 24 hour periods passed?

To get the first, the easiest way would be to simply install a modern date/time package like Luxon:

npm install luxon

Then it's a simple matter of asking it:

var end   = DateTime.fromISO('2017-03-13');
var start = DateTime.fromISO('2017-02-13');

var diffInMonths = end.diff(start, 'days');
diffInDays.toObject(); //=> { days: 13 }

To get the latter, just do a little arithmetic:

  • 1 day is 24 hours;
  • 1 hour is 60 minutes;
  • 1 minute is 60 seconds;
  • 1 second is 1000 milliseconds

Hence 1 day is 86,400,000 milliseconds (24 * 60 * 60 * 60).

const DAY = 24 * 60 * 60 * 1000;
const diffInMilliseconds = dt1 - dt2 ;
const diffInDays = diffInMilliseconds / DAY ;

that will give you fractional days: use Math.round(), Math.floor(), or Math.ceil() as appropriate to get rid of the fractional part.j

You can get the former via arithmetic, too, it's just a little more complicated:

function dateDiffInCalendarDays( dtFrom, dtThru ) {
  // clone the arguments, and allow numeric timestamps
  const from = new Date(dtFrom) ;
  const thru = new Date(dtThru) ;
  
  // set the time components to midnight/start-of-day
  from.setHours(0,0,0,0);
  thru.setHours(0,0,0,0);

  const deltaInWholeDays = thru - from;

  return deltaInWholeDays;
}
  • Related