0

I know there are lots of questions similar to this, but all the examples I can find are asking how to get the absolute number of days difference.

How could I get the number of relative days between a date (epoch seconds) and the current time in Javascript e.g.

function getDaysDelta(secs) {
    var hoursDelta = Math.ceil((secs - NOW_SECS) / 3600);
    ????
} 

If it's 22:00 now and the supplied value is for 04:00 the following day, I would expect the function to return 1, because there is 1 day in the difference. Likewise, if it's 04:00 now, and the supplied value is for 22:00 the previous day, I would expect the function to return -1. It should return 0 if the supplied value falls sometime within today.

I would like to avoid pulling in a monster dependency, so pure JS is preferable, although I do already have a dependency on jQuery (v2), so solutions involving that are fine.

RTF
  • 6,214
  • 12
  • 64
  • 132

2 Answers2

1

You could just remove the time from both dates, see following please:

var MS_PER_DAY = 1000 * 60 * 60 * 24;

function dateDiffInDays(a, b) {
  //Ignore time and timezone
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.floor((utc2 - utc1) / MS_PER_DAY);
}

var d11 = new Date(2017, 6, 26, 22);
var d12 = new Date(2017, 6, 26, 4);

console.log("Example 1");
console.log(d11.toLocaleString());
console.log(d12.toLocaleString());
console.log("Diff: ", dateDiffInDays(d11, d12));

var d21 = new Date(2017, 6, 26, 22);
var d22 = new Date(2017, 6, 27, 4);

console.log("\nExample 2");
console.log(d21.toLocaleString());
console.log(d22.toLocaleString());
console.log("Diff: ", dateDiffInDays(d21, d22));

var d21 = new Date(2017, 6, 27, 22);
var d22 = new Date(2017, 6, 26, 4);

console.log("\nExample 3");
console.log(d21.toLocaleString());
console.log(d22.toLocaleString());
console.log("Diff: ", dateDiffInDays(d21, d22));

I hope it helps you, bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70
0

How about this?

let dayDifference = Math.floor((secs.getTime() - NOW_SECS.getTime()) / 1000 / 3600 / 24);

secs and NOW_SECS are both javascript dates.

It's better to use getTime() before date computation for clarity. getTime() return the unix timestamp in milliseconds. Javascript does it implicitly when substracting dates, but fails if you want to add (+) seconds/hours/... to a date. It will convert date to a string and concatenate.

Samy
  • 1,651
  • 1
  • 11
  • 12
  • Does `NOW_SECS` means EPOCH? please be specific. this answer is of very low quality otherwise :( – vsync Jun 26 '17 at 09:11