calculate difference between two times in moment js [duplicate]

坚强是说给别人听的谎言 提交于 2021-02-17 04:43:44

问题


I'm writing a service in node js. I have used moment js for time related solutions. I want to calculate the time difference between two times. Here is my snippet and it's not giving me the desired output :

var now = moment('11:08:30',"H:mm:ss");
var prev = moment('11:07:30', "H:mm:ss");
var result = moment(now.diff(prev)).format("H:mm:ss");
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

As per my understanding, I think the difference between 11:08:30 and 11:07:30 should come out as 00:01:00 but instead the output is coming as 5:31:00. I don't understand why this is happening. How do I fix it so that the output is 00:01:00 i.e 1 minute ?


回答1:


This is a working example,

var now = moment('11:08:30',"H:mm:ss");
var prev = moment('11:07:30', "H:mm:ss");

 function dateDifference(startDate, endDate){
        return moment(startDate).diff(moment(endDate), 'seconds');
    }
    console.log(this.dateDifference(now,prev))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

The supported measurements are years, months, weeks, days, hours, minutes, and seconds. For ease of development, the singular forms are supported as of 2.0.0. Units of measurement other than milliseconds are available in version 1.1.1.


Now, once u get answer in seconds, then please follow this link to convert seconds into your desired format 'h:mm:ss'

format seconds into 'hh:mm:ss'



来源:https://stackoverflow.com/questions/53532750/calculate-difference-between-two-times-in-moment-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!