Home > database >  Find date difference without knowing the exact timestamp/day
Find date difference without knowing the exact timestamp/day

Time:07-05

I have found my self in a bit of complication. I need to find the difference between two days timestamps' in milliseconds without predefining any of them. All I know is that I need the small timestamp to be now which I guess I can get by using Date.now() (correct me if I'm wrong). The other timestamp can be any day of the week and I have no control over which the user picks.

So I want something like this:

var dif = The future thursday - now

I only know the days in words. I do not know how to then change that to timestamp in milliseconds.

CodePudding user response:

You can get the next instance of a particular day of the week from another day of the week by arithmetic. You can then get the difference between that date and midnight at the start of a specific day, e.g.

// Get next instance of particular weekday.
// ECMAScript day numbering, i.e. 0 = Sunday, 1 = Monday, etc.
// If targetDay == currentDay, get next instance of day
function getNextWeekday(targetDay, date = new Date()) {
  let d = new Date(date);
  // For targetDay, make Sunday 7 not 0
  targetDay = targetDay || 7;
  d.setDate(
    d.getDate()   (((targetDay - d.getDay()   7) % 7) || 7)
  );
  return d;
}

// Get time difference in milliseconds between
// 00:00 on the targetDay from 00:00 on supplied date.
function getTimeDiff(targetDay, date = new Date()) {
  let d = getNextWeekday(targetDay, date);
  return d.setHours(0,0,0,0) - new Date(date).setHours(0,0,0,0);
}

// The following might return fractional days were the
// calculation crosses a DST boundary
// Get timeDiff to next Sunday
let timeDiff = getTimeDiff(0);
console.log(`${timeDiff} (${timeDiff/8.64e7} days)`);

CodePudding user response:

dude, use moment for date/time js stuff it will make your life way easier.

https://momentjs.com/

you can find in its documentation everything you are searching for

  • Related