How to calculate date difference in JavaScript?

前端 未结 18 1781
执笔经年
执笔经年 2020-11-22 03:41

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

18条回答
  •  忘了有多久
    2020-11-22 04:09

    based on javascript runtime prototype implementation you can use simple arithmetic to subtract dates as in bellow

    var sep = new Date(2020, 07, 31, 23, 59, 59);
    var today = new Date();
    var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
    console.log('Day Diff: '+diffD);
    

    the difference return answer as milliseconds, then you have to convert it by division:

    • by 1000 to convert to second
    • by 1000×60 convert to minute
    • by 1000×60×60 convert to hour
    • by 1000×60×60×24 convert to day

提交回复
热议问题