Get the days, hours and minutes in Moment.js

前端 未结 4 852
情话喂你
情话喂你 2020-12-03 13:24

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: 2         


        
4条回答
  •  感动是毒
    2020-12-03 13:58

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

提交回复
热议问题