本文介绍了如何计算两个日期之间的年数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想得到两个日期之间的年数。我可以得到这两天之间的天数,但是如果我把它除以365,结果是不正确的,因为有几年有366天。这是我的代码获取日期差异:
var birthday = value; // format 01/02/1900
var dateParts = birthday。分裂(/);
var checkindate = new Date(dateParts [2],dateParts [0] - 1,dateParts [1]);
var now = new Date();
var difference = now - checkindate;
var days =差异/(1000 * 60 * 60 * 24);
var thisyear = new Date()。getFullYear();
var birthyear = dateParts [2];
var number_of_long_years = 0; $($ y = 0)= $($)$($)$($) y%400 == 0){
number_of_long_years ++;
}
}
日期计数完美。我正在尝试添加额外的日子,这是一个366天的一年,我正在做这样的事情:
var years =((days)*(thisyear-birthyear))
/((number_of_long_years * 366)+((thisyear-birthyear-number_of_long_years)* 365));
我得到年数。这是正确的,还是有更好的方法呢?
解决方案
这对你有帮助:
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++;
}
}
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) );
I'm getting the year count. Is this correct, or is there a better way to do this?
解决方案
this can be helpful for you:
http://romcartridge.blogspot.com/2010/01/javascript-function-to-calculate-age.html
这篇关于如何计算两个日期之间的年数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!