moment获取几小时前,在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.

解决方案

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值