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

Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

var difference = date2 - date1;

From there, you can use simple arithmetic to derive the other values.

查看更多
余生无你
3楼-- · 2018-12-31 08:35
<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split('/');
  var str2= time2.split('/');

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS + ' ms');

  var diffS = diffMS / 1000;    
  console.log(diffS + ' ');

  var diffM = diffS / 60;
  console.log(diffM + ' minutes');

  var diffH = diffM / 60;
  console.log(diffH + ' hours');

  var diffD = diffH / 24;
  console.log(diffD + ' days');
  alert(diffD);
}

//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff('10/18/2013','10/14/2013')" 
       value="clickHere()" />

</body>
</html>
查看更多
只靠听说
4楼-- · 2018-12-31 08:36
function DateDiff(date1, date2) {
    date1.setHours(0);
    date1.setMinutes(0, 0, 0);
    date2.setHours(0);
    date2.setMinutes(0, 0, 0);
    var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference 
    return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value      
}
查看更多
大哥的爱人
5楼-- · 2018-12-31 08:36

If you are using moment.js then it is pretty simple to find date difference.

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")
查看更多
听够珍惜
6楼-- · 2018-12-31 08:39

Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.

Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.

var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();

// Reset someday to the current year.
someday.setFullYear(today.getFullYear());

// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
    years--;
}
document.write("Its been " + years + " full years.");
查看更多
闭嘴吧你
7楼-- · 2018-12-31 08:39

you can also use this very easy to use date manipulation library http://www.datejs.com/

ex:

// Add 3 days to Today
Date.today().add(3).days();

(Works very well with date formatting libraries)

查看更多
登录 后发表回答