Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...