Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 

What I want to get is:

Day: 3 Hours: 3 Mins: 3 

I tried the following code:

const now = moment(); const exp = moment(expire_date); console.log(expire_date); days = exp.diff(now, 'days'); hours = exp.diff(now, 'hours') - (days * 24); minutes = exp.diff(now, 'minutes') - ((days * 1440) + (hours * 24) * 60); 

I know I did something wrong (maybe my calculation or I used the wrong method), but I can't figure out what it is.

like image 853
I am L Avatar asked Jan 26 '17 14:01

I am L


People also ask

How do you find the minutes from a date moment?

The moment(). minute() Method is used to get the minutes from the current time or to set the minutes. moment(). minutes();

How do you extract time from a moment?

To extract time from moment. js object with JavaScript, we can use the format method. const time = moment("2022-01-16T12:00:00").

How do you find the number of days in a month with moments?

The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.


2 Answers

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 moments  const diff = expiration.diff(now);    //express as a duration  const diffDuration = moment.duration(diff);    // display  console.log("Days:", diffDuration.days());  console.log("Hours:", diffDuration.hours());  console.log("Minutes:", diffDuration.minutes());
<script src="https://momentjs.com/downloads/moment.js"></script>
like image 148
gotomanners Avatar answered Sep 20 '22 18:09

gotomanners


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)
<script src="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

like image 26
alebianco Avatar answered Sep 19 '22 18:09

alebianco