Skip to content Skip to sidebar Skip to footer

Get The Days, Hours And Minutes In Moment.js

So This is my first time using Moment.js and I encountered the following problem, so I have this following dates: now: 2017-01-26T14:21:22+0000 expiration: 2017-01-29T17:24:22+0000

Solution 1:

MomentJS can calculate all that for you without you doing any logic.

  • First find the difference between the two moments
  • Express it as a Duration
  • Then display whichever component .days(), .hours() of the duration that you want.

Note: You can also express the entire duration .asDays(), .asHours() etc if you want.

const now = moment("2017-01-26T14:21:22+0000");
const expiration = moment("2017-01-29T17:24:22+0000");

// get the difference between the momentsconst diff = expiration.diff(now);

//express as a durationconst diffDuration = moment.duration(diff);

// displayconsole.log("Days:", diffDuration.days());
console.log("Hours:", diffDuration.hours());
console.log("Minutes:", diffDuration.minutes());
<scriptsrc="https://momentjs.com/downloads/moment.js"></script>

Solution 2:

this will give you the right values and remove the headache of manual calculations

let expiration = "2017-01-29T17:24:22+0000"const now = moment();
const exp = moment(expiration);

console.log(exp.format());

days = exp.diff(now, 'days');
hours = exp.subtract(days, 'days').diff(now, 'hours');
minutes = exp.subtract(hours, 'hours').diff(now, 'minutes');

console.log(days, hours, minutes)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

note that the substract operations will mutate the original exp value, so don't go passing it around expecting it to be the original date

Solution 3:

Try my solution. I think that is it:

var now = moment("2017-01-26T14:21:22+0000");
  var expiration = moment("2017-01-29T17:24:22+0000");
  var minsAverage = expiration.diff(now, "minutes");

  var min = parseInt(minsAverage % 60);
  var hours = parseInt(minsAverage / 60);
  var days = parseInt(hours / 24);
  hours = hours - 24*days;

Solution 4:

For more information check the documentation https://momentjs.com/docs/#/displaying/difference/

var now = moment()
var exp = moment().add(1,'days')
var days = exp.diff(now, 'days')
var months = exp.diff(now, 'months')
var years = exp.diff(now, 'years', true) //float numberconsole.log(now,exp,days, months, years)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Post a Comment for "Get The Days, Hours And Minutes In Moment.js"