Home > Back-end >  Using moment for time to calculate differnce
Using moment for time to calculate differnce

Time:03-22

I have two date:

const a = moment(start)
const b = moment(end)

where for example: a "2022-03-22T09:00:00.000Z" b "2022-03-22T09:30:00.000Z"

Now I'm interested to calculate only difference about time.

So for example if I do moment.duration(b.diff(a))) i obtain PM30

But what I would to obtain is the difference like:

`a  "2022-03-22T09:00:00.000Z"  b  "2022-03-22T09:30:00.000Z"`   => b - a = 0.5
`a  "2022-03-22T09:00:00.000Z"  b  "2022-03-22T10:30:00.000Z"`   => b - a = 1.5

How can I do?

CodePudding user response:

to get in hours add .asHours()

var a = moment('2022-03-22T09:00:00.000Z');//now
var b = moment('2022-03-22T10:30:00.000Z');

console.log(moment.duration(b.diff(a)).asHours());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

This can be easily computed using standard JavaScript Dates without incurring the additional overhead in case that's an option to you:

const SEC = 1000, MIN = SEC * 60, HOUR = MIN * 60, DAY = HOUR * 24;
const a = new Date("2022-03-22T09:00:00.000Z");
const b = new Date("2022-03-22T09:30:00.000Z");
const diff = b - a;

console.log("Time difference is:\n"  
    `${diff} milliseconds or\n`  
    `${diff / SEC} seconds or\n`  
    `${diff / MIN} minutes or\n`  
    `${diff / HOUR} hours or\n`  
    `${diff / DAY} days`);

  • Related