Fix age calc, missing leap day for years divisible by 100 and not by 400 (#96)

This commit is contained in:
czifumasa
2022-04-27 17:16:23 +02:00
committed by GitHub
parent 359d07e1ec
commit 35259e5767
2 changed files with 27 additions and 4 deletions

View File

@@ -32,6 +32,18 @@ describe('calcAge()', () => {
const age = calcAge('2 Sep 1990', '1 Sep 2021', intl);
expect(age).toEqual('30 years');
});
it('age respecting missing leap year divisible by 100 and not divisible by 400', () => {
const age = calcAge('1890', '1921', intl);
expect(age).toEqual('31 years');
});
it('age respecting missing leap year divisible by 100 and not divisible by 400 for full dates', () => {
const age = calcAge('1 Sep 1890', '1 Sep 1921', intl);
expect(age).toEqual('31 years');
});
it('age with round down respecting missing leap year divisible by 100 and not divisible by 400', () => {
const age = calcAge('2 Sep 1890', '1 Sep 1921', intl);
expect(age).toEqual('30 years');
});
it('age with exact and range between', () => {
const age = calcAge('1990', 'BET 2020 AND 2021', intl);

View File

@@ -115,10 +115,21 @@ function calcDateDifferenceInYears(
const firstDateObject = toDateObject(firstDate);
const secondDateObject = toDateObject(secondDate);
const dateDiff = new Date(
secondDateObject.valueOf() - firstDateObject.valueOf(),
);
return Math.abs(dateDiff.getUTCFullYear() - 1970);
const startYear = firstDateObject.getUTCFullYear();
let yearDiff = secondDateObject.getUTCFullYear() - startYear;
let monthDiff = secondDateObject.getUTCMonth() - firstDateObject.getUTCMonth();
if (monthDiff < 0) {
yearDiff--;
monthDiff += 12;
}
const dayDiff = secondDateObject.getUTCDate() - firstDateObject.getUTCDate();
if (dayDiff < 0) {
if (monthDiff <= 0) {
yearDiff--;
}
}
return Math.abs(yearDiff);
}
export function calcAge(