Skip to main content
Inspiring
December 13, 2018
Answered

Difference between dates is 1 day short

  • December 13, 2018
  • 1 reply
  • 945 views

Can someone please tell me why the result of this script is one day short? (The date fields are formatted mm/dd/yyyy)

     Ex: the difference between 01/01/2019 and 12/31/2018 == 0 instead of == 1

//dateEnd

  var actual = this.getField("date.Actual.Closing").value;

  var dateEnd = util.scand("mm/dd/yyyy", actual); //get date object for end date

//Start date: construct it from dateEnd as 12/31/ of the yyyy before dateEnd

  var yr = this.getField("date.YearPrior");

  var year = dateEnd.getFullYear();

    yr.value = year - 1

  var strStart = this.getField("date.LastDec31");

    strStart.value = util.printd("mm/dd/yyyy", new Date("12/31/" + yr.value));

  var dateStart = util.scand("mm/dd/yyyy", strStart.value);

//Calculate and assign the date difference

  var dDiff = dateEnd.getTime() - dateStart.getTime(); /

  var oneDay = 24 * 60 * 60 * 1000;

  var days = this.getField("num.days");

    days.value = Math.floor(dDiff / oneDay);

This topic has been closed for replies.
Correct answer Test Screen Name

I'd be wary of using floor, because you are assuming that the millisecond values are held and calculated exactly, and I'd worry about leap seconds.

I suggest you display the actual values of dateEnd.getTime() and dateStart.getTime(), to see if that's the problem.

1 reply

Test Screen NameCorrect answer
Legend
December 13, 2018

I'd be wary of using floor, because you are assuming that the millisecond values are held and calculated exactly, and I'd worry about leap seconds.

I suggest you display the actual values of dateEnd.getTime() and dateStart.getTime(), to see if that's the problem.

ODuinnAuthor
Inspiring
December 13, 2018

Bingo, and thank you.

I did what you suggested, calculated the difference between the two .getTime() values and then calculated the number of days based on the difference. My script as posted above was taking, for example, an 11 day difference and calculating the "getTime()" difference as 10.999999953703703, after which Math.floor was rounding it down to the integer 10. By changing Math.floor to Math.ceil the error was corrected, which is what I need since the difference in my form must always round a partial day up to the next integer.