moment.js diff date formatting

后端 未结 2 1198
名媛妹妹
名媛妹妹 2021-02-13 05:51

I\'m using moment.js and want to calculate the difference between two timestamp,format them afterwards and display them in a div.

var diffTime = moment(13903101         


        
2条回答
  •  梦毁少年i
    2021-02-13 06:20

    moment.duration should be used

       let startTime = moment('09:45:20', 'h:mm:ss A').format("HH:mm:ss");
       let endTime = moment('10:30:35', 'h:mm:ss A').format("HH:mm:ss")
       var todayDate = moment(new Date()).format("MM-DD-YYYY"); //Can change, based on the requirement
       var startDate = new Date(`${todayDate} ${startTime}`);
       var endDate = new Date(`${todayDate} ${endTime}`);
       var diffTime = moment(endDate).diff(startDate);
    
       var duration = moment.duration(diffTime);
       var years = duration.years(),
        days = duration.days(),
        months = duration.months(),
        hrs = duration.hours(),
        mins = duration.minutes(),
        secs = duration.seconds();
    
    var div = document.createElement('div');
    div.innerHTML = years + ' years ' + months + 'months ' + days + ' days ' + hrs + ' hrs ' + mins + ' mins ' + secs + ' sec';
    document.body.appendChild(div);
    

    jsfiddle

提交回复
热议问题