javascript:计算两个日期之间的差异 [英] javascript: Calculate difference between two dates

查看:105
本文介绍了javascript:计算两个日期之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到两个日期之间的区别。为此,我从另一个Date对象中减去了一个Date对象。我的代码如下:

I want to find difference between two Dates. For that I did subtract one Date object from another Date object. My code is as follows :

var d1 = new Date(); //"now"
var d2 = new Date(2012,3,17); // before one year
document.write("</br>Currrent date : "+d1);
document.write("</br>Other Date : "+d2);
document.write("</br>Difference : "+new Date(Math.abs(d1-d2)));

但结果并非如我所料:

当前日期:太阳2月17日2013 02:58:16 GMT-0500(美国东部时间)

其他日期:星期六2012年1月21日00:00:00 GMT-0500(EST)< br>
差异:1971年1月28日星期四21:58:16 GMT-0500(EST)

我想计算(1年)他们之间的区别。

I want to calculate the (1 year) difference between them.

谢谢

推荐答案

所以从根本上说,最大的确切日期单位是,其占7 * 86400秒。月份和年份不是明确定义的。所以假设你想说1个月前,如果两个日期是例如 5.1.2013 5.2.2013 5.2.2013 5.3.2013 。并说1个月和1天前如果你有例如 5.1.2013 6.2.2013 ,那么你必须使用这样的计算:

So fundamentally the biggest exact date unit is a week which accounts for 7 * 86400 seconds. Months and Years are not exaclty defined. So assuming you want to say "1 Month ago" if the two dates are e.g. 5.1.2013 and 5.2.2013 or 5.2.2013 and 5.3.2013. And saying "1 Month and 1 day ago" if you have e.g. 5.1.2013 and 6.2.2013, then you would have to use a calculation like this:

// dateFrom and dateTo have to be "Date" instances, and to has to be later/bigger than from.
function dateDiff(dateFrom, dateTo) {
  var from = {
    d: dateFrom.getDate(),
    m: dateFrom.getMonth() + 1,
    y: dateFrom.getFullYear()
  };

  var to = {
    d: dateTo.getDate(),
    m: dateTo.getMonth() + 1,
    y: dateTo.getFullYear()
  };

  var daysFebruary = to.y % 4 != 0 || (to.y % 100 == 0 && to.y % 400 != 0)? 28 : 29;
  var daysInMonths = [0, 31, daysFebruary, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  if (to.d < from.d) {
    to.d   += daysInMonths[parseInt(to.m)];
    from.m += 1;
  }
  if (to.m < from.m) {
    to.m   += 12;
    from.y += 1;
  }

  return {
    days:   to.d - from.d,
    months: to.m - from.m,
    years:  to.y - from.y
  };
}
// Difference from 1 June 2016 to now
console.log(dateDiff(new Date(2016,5,1), new Date()));

正如我所说,它变得棘手;)

As I said, it gets tricky ;)

这篇关于javascript:计算两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆