How to calculate date difference in javascript

2018-12-31 07:57发布

I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds, how can I do it? Please suggest.

14条回答
还给你的自由
2楼-- · 2018-12-31 08:55

use Moment.js for all your JavaScript related date-time calculation

Answer to your question is:

var a = moment([2007, 0, 29]);   
var b = moment([2007, 0, 28]);    
a.diff(b) // 86400000  

Complete details can be found here

查看更多
呛了眼睛熬了心
3楼-- · 2018-12-31 08:57
var d1=new Date(2011,0,1); // jan,1 2011
var d2=new Date(); // now

var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days;
diff/=sign; // or diff=Math.abs(diff);
diff=(diff-(milliseconds=diff%1000))/1000;
diff=(diff-(seconds=diff%60))/60;
diff=(diff-(minutes=diff%60))/60;
days=(diff-(hours=diff%24))/24;

console.info(sign===1?"Elapsed: ":"Remains: ",
             days+" days, ",
             hours+" hours, ",
             minutes+" minutes, ",
             seconds+" seconds, ",
             milliseconds+" milliseconds.");
查看更多
登录 后发表回答