获取Moment.js中的日,小时和分钟

时间:2017-01-26 14:26:24

标签: javascript momentjs

所以这是我第一次使用Moment.js,我遇到了以下问题,所以我有以下日期:

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);

我知道我做错了(也许是我的计算或者我使用了错误的方法),但我无法弄清楚它是什么。

4 个答案:

答案 0 :(得分:28)

MomentJS可以在不做任何逻辑的情况下为你计算所有这些。

  • 首先找出两个时刻之间的区别
  • 将其表示为持续时间
  • 然后显示您想要的持续时间的.days().hours()组件。

注意:如果需要,您还可以表达整个期限.asDays().asHours()等。

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>

答案 1 :(得分:4)

这将为您提供正确的值并消除手动计算的麻烦

&#13;
&#13;
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)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
&#13;
&#13;
&#13;

请注意,substract操作会改变原来的exp值,因此请不要将其传递给期望它是原始日期

答案 2 :(得分:1)

试试我的解决方案。我认为就是这样:

  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;

答案 3 :(得分:0)

有关详细信息,请查看文档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 number

console.log(now,exp,days, months, years)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>