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?
To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.
Sleek foundation javascript function.
function calculateAge(birthday) { // birthday is a date var ageDifMs = Date.now() - birthday; var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); }
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.
The diff
method is probably what you want: http://momentjs.com/docs/#/displaying/difference/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With