How to get difference between times in decimal in moment js?

天大地大妈咪最大 提交于 2021-02-05 10:55:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!