0

Am trying to get the diference between two dates in hours and minutes. That is between 06/24/2018 17:49:29 and 06/24/2018 21:45:30. THese dates value are dynamic but just as an example

So i have tried

    var date1 = new Date("06/24/2018 17:49:29");
    var date2 = new Date("06/24/2018 21:45:30");
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var difhours = Math.ceil(timeDiff / (1000 * 3600)); 
    console.log(difhours);

The above gives me 4 but the difference is not 4 as there are minutes

In my expectation i expect the difference to be

17:49:29 - 18:00:00 = 1.19  //i hour and 19 minutes

18:00:00 to 21:00:00  that is 3 hours

21:00:00 to 21:45:30  that is 45  minutes

Adding the above should give me 5.04 that is 5 hours and 4 minutes, since an hour has 60 minutes

What else do i need to add to make this work

I have checked on This question but it doesnt give a solution am looking for.

I have also tried

function dateDiffInHours(date1, date2) {
 var msDiff = date2.getTime() - date1.getTime();
  return msDiff / 3600000;
}
console.log("06/24/2018 17:49:29","06/24/2018 21:45:30")

THe above gives me 3.93 which is wrong

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 1
    I'm confused about your assertions. As far as I know 1.19 isn't 1 hour and 19 minutes because decimal goes to 99 not 60, but it's possible I'm not understanding. – zfrisch Jun 26 '18 at 15:23
  • _“The above gives me 4 but the difference is not 4 as there are minutes”_ - yes, but since you used `Math.ceil` on a `4.x` value, of course you only get `4` as a result. _“What else do i need to add to make this work”_ - the math behind this is absolutely trivial. You got your value of 4, so now you simply subtract 4*60 from the original value … and what’s left is the excess minutes. – CBroe Jun 26 '18 at 15:24
  • @zfrisch am expressing this in terms of hours and minutes hence the 1.19 also could be 1:19, not sure – Geoff Jun 26 '18 at 15:30
  • @CBroe i would like to feature the minutes in the result – Geoff Jun 26 '18 at 15:31
  • http://jsfiddle.net/mplungjan/40bq58co/ – mplungjan Jun 26 '18 at 15:32

0 Answers0