shorif2000
shorif2000

Reputation: 2654

moment date difference is not working

I am trying to do date difference using moment but it is showing incorrect days figure

var before = moment('25-Sep-2017 13:44','DD-MMM-YYYY HH:mm');
var now = moment('25-Sep-2017 13:46','DD-MMM-YYYY HH:mm');

console.log(
  moment(now - before)
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Upvotes: 0

Views: 1311

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

Use moment diff to calculate the difference between two moment objects, instead of -, so you will have now.diff(before) instead of moment(now - before).

Then you can use moment.duration(Number); to create a duration:

Moment.js also has duration objects. Where a moment is defined as single points in time, durations are defined as a length of time.

You can use moment-duration-format plug-in to get the duration value in the form of: 'D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]'. See format method docs for more info.

Note that using moment-duration-format:

Leading tokens are automatically trimmed when they have no value.

you can use { trim: false } option to stop that behavior.

Here a live sample:

var before = moment('25-Sep-2017 13:44','DD-MMM-YYYY HH:mm');
var now = moment('25-Sep-2017 13:46','DD-MMM-YYYY HH:mm');

console.log(
  moment.duration( now.diff(before) )
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);

// With trim: false
console.log(
  moment.duration( now.diff(before) )
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]', { trim: false })
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

Upvotes: 1

Related Questions