Moment JS - calculating duration in hours betwen 2 dates
Asked Answered
C

3

8

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/.

Cockadoodledoo answered 21/2, 2016 at 23:7 Comment(1)
Possible duplicate of Get hours difference between two dates in Moment JsWane
C
18

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
Chery answered 21/2, 2016 at 23:11 Comment(0)
C
6

This is a bit more succinct than the accepted answer:

const startTime = moment('2016-02-21 18:00', 'YYYY/MM/DD HH:mm');
const endTime = moment('2016-02-21 19:30', 'YYYY/MM/DD HH:mm');

const hoursDiff = endTime.diff(startTime, 'hours', true);

console.log(hoursDiff); // 1.5
Creamer answered 12/11, 2019 at 17:16 Comment(0)
S
0

You just need to use the date.diff() method in moment.js

const now = moment.utc();
var end = moment("2022-11-08"); 
var hours = now.diff(end, "hours"); 
console.log(hours)
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Starr answered 9/11, 2022 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.