0

Trying to change this function from Get difference between 2 dates in javascript? to return difference in hours instead of days, but no luck so far. =)

function dateDiffInDays(scheduled, due) {
    var _MS_PER_DAY = 1000 * 60 * 60 * 24;
    var scheduled = new Date(scheduled);
    var due = new Date(due);
    var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
    var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());
    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

Changed _MS_PER_DAY to 1000 * 60 * 60, but it wont work returning zeros. Please help.

EDIT: values of schedule and due in this format: "09/21/2014 09:00:00 am"

Community
  • 1
  • 1
Alex G
  • 3,048
  • 10
  • 39
  • 78
  • What *are* the values of utc1 and utc2? If 0 is returned then both utc1 and utc2 represent the *same* day (and same hour in the day). – user2864740 Sep 21 '14 at 05:46
  • That is incorrect (-1 and a vote to close for not including the *real* **utc1** and **utc2** values). Try again - I can say this is incorrect with certainty because the hours are *not transferred* over to the `Date.UTC` function call. – user2864740 Sep 21 '14 at 05:47
  • Again, what are the *actual* values of `utc1` and `utc2` start there. Then problem and solution, which does include copying over the relevant precision, will become apparent. Also, which fields are copied over (and if new Date objects should be created) depends on *what rules* should be used - e.g. is 10:55 still "one hour" after 9:05? – user2864740 Sep 21 '14 at 05:53

1 Answers1

1

In your question, these lines:

var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());

Scrub the hour/minute/etc. information from the dates, so if the two dates fall on the same day, the result will always be zero.

A much simpler function can be used to get the difference in hours (as a decimal number):

function dateDiffInHours(date1, date2) {
    var msDiff = date2.getTime() - date1.getTime();
    return msDiff / 3600000;
}

Or if you want it as a rounded/floored int, then apply Math.round() or Math.floor() to the returned result.

Converting to UTC at all is unnecessary.

AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
  • `function dateDiffInHours(scheduled, due) { var scheduled = new Date(scheduled); var due = new Date(due); var msDiff = (due.getTime() - scheduled.getTime()) / 3600000; return msDiff.toFixed(2); }` – Alex G Sep 21 '14 at 06:07