Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment JS - calculating duration in hours betwen 2 dates

Having some issues with calculating a date time range. What im trying to accomplish is to have moment provide me the difference in hours.

For example, here is my script:

    var startTime = $('2016-02-21 18:00');
    var endTime = $('2016-02-21 19:30');
    var hours = moment(endTime, 'YYYY/MM/DD HH:mm').diff(moment(startTime, 'YYYY/MM/DD HH:mm')).duration().asHours();
console.log(hours);

I am expecting that my console.log(hours) returns something like 1.5 (estimated in hours). But instead it's returning this error:

Uncaught TypeError: moment(...).diff(...).duration is not a function
    at <anonymous>:5:90
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

Would anyone have any ideas?

Heres a full example here https://jsfiddle.net/ewmq6sof/.

like image 661
Daniel Ellison Avatar asked Feb 21 '16 23:02

Daniel Ellison


People also ask

How do you find the difference between two dates in hours in a moment?

If you are using a date and time field and would like to output the difference between the two dates in days, hours and minutes, use the following template: var m1 = moment('{admission}', 'DD-MM-YYYY HH:mm'); var m2 = moment('{discharge}', 'DD-MM-YYYY HH:mm'); var m3 = m2. diff(m1,'minutes'); var m4 = m2.

How do you subtract two dates in a moment?

You are correct, you can use moment's diff function to subtract two dates (see my example on Plunker): var date1 = moment('2016-10-08 10:29:23'); var date2 = moment('2016-10-08 11:06:55'); var diff = date2. diff(date1); Diff will be equal to 2252000 , the number of milliseconds between the two date.

How do you calculate reaction time difference?

var days = Math. floor(distance / (1000 * 60 * 60 * 24)); var hours = Math. floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math. floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.


1 Answers

You need to wrap the difference in the duration:

var startTime = '2016-02-21 18:00';
var endTime = '2016-02-21 19:30';
var hours = moment
        .duration(moment(endTime, 'YYYY/MM/DD HH:mm')
        .diff(moment(startTime, 'YYYY/MM/DD HH:mm'))
        ).asHours();
console.log(hours); // 1.5
like image 94
baao Avatar answered Sep 18 '22 02:09

baao