如何计算两个日期之间的年数? [英] How can I calculate the number of years between two dates?

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

问题描述

我想获取两个日期之间的年数。我可以得到这两天之间的天数,但是如果我将其除以365,结果将是不正确的,因为某些年份有366天。

I want to get the number of years between two dates. I can get the number of days between these two days, but if I divide it by 365 the result is incorrect because some years have 366 days.

这是我的代码获取日期差:

This is my code to get date difference:

var birthday = value;//format 01/02/1900
var dateParts = birthday.split("/");

var checkindate = new Date(dateParts[2], dateParts[0] - 1, dateParts[1]);   
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);

var thisyear = new Date().getFullYear();
var birthyear = dateParts[2];

    var number_of_long_years = 0;
for(var y=birthyear; y <= thisyear; y++){   

    if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {

                    number_of_long_years++;             
    }
}   

日期计数非常有效。我正在尝试添加一年为366天的其他日子,并且我正在执行以下操作:

The day count works perfectly. I am trying to do add the additional days when it is a 366-day year, and I'm doing something like this:

var years = ((days)*(thisyear-birthyear))
            /((number_of_long_years*366) + ((thisyear-birthyear-number_of_long_years)*365) );

我正在计算年份。

推荐答案

可能不是您要找的答案,但是以2.6kb的速度,我不会尝试重新发明轮子,而是使用 moment.js 。没有任何依赖性。

Probably not the answer you're looking for, but at 2.6kb, I would not try to reinvent the wheel and I'd use something like moment.js. Does not have any dependencies.

diff 方法可能就是您想要的: http://momentjs.com/docs/#/displaying/difference/

The diff method is probably what you want: http://momentjs.com/docs/#/displaying/difference/

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

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