Jon Sud
Jon Sud

Reputation: 11641

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

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 });

Upvotes: 2

Views: 2447

Answers (2)

Patrick_Weber
Patrick_Weber

Reputation: 120

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);

Upvotes: 4

Michiel
Michiel

Reputation: 353

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

Upvotes: 0

Related Questions