问题
How to get the difference between times in decimal in moment js?
For example: in: '17:39', out: '21:10'.
I try to do this code but it's not work for me:
let startTime = project[0].in;
let end = project[0].out;
startTime = moment(startTime, ['H:m']);
end = moment(end, ['H:m']);
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();
var minutes = parseInt(duration.asMinutes()) % 60;
console.log({ hours, minutes });
const a = duration.asMinutes(); //moment.duration('1:30').asHours();
console.log({ a });
回答1:
The diff function in moment js also accepts a third argument to output decimals, as seen in the docs
const moment = require('moment');
const start = moment('21:10', 'HH:mm');
const end = moment('17:39', 'HH:mm');
const difference = start.diff(end, 'hours', true);
回答2:
I'm not totally sure what your expected output should be in your example, maybe the following code will help you.
const moment = require('moment');
const start = moment('21:10', 'HH:mm');
const end = moment('17:39', 'HH:mm');
const difference = start.diff(end);
const duration = moment.duration(difference);
const minutes = duration.asMinutes() % 60;
const hours = Math.floor(duration.asMinutes() / 60);
console.log(hours + ':' + minutes); // 3:31
来源:https://stackoverflow.com/questions/55069681/how-to-get-difference-between-times-in-decimal-in-moment-js