在Moment.js中获取日期,小时和分钟 [英] Get the days, hours and minutes in Moment.js
本文介绍了在Moment.js中获取日期,小时和分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以这是我第一次使用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
我想得到的是:
Day: 3
Hours: 3
Mins: 3
我尝试了以下代码:
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.
推荐答案
MomentJS可以为您计算所有内容,而无需您执行任何逻辑.
MomentJS can calculate all that for you without you doing any logic.
- 首先找到两个时刻之间的差异
- 将其表示为持续时间
- 然后显示所需持续时间的任意部分
.days()
,.hours()
.
- 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.
注意:如果需要,您还可以表示整个持续时间.asDays()
,.asHours()
等.
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>
这篇关于在Moment.js中获取日期,小时和分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文