Skip to content

Instantly share code, notes, and snippets.

@MaxXx1313
Last active May 20, 2020 11:49
Show Gist options
  • Save MaxXx1313/7f15eccff74037423533b62bfdfdff37 to your computer and use it in GitHub Desktop.
Save MaxXx1313/7f15eccff74037423533b62bfdfdff37 to your computer and use it in GitHub Desktop.
Calculate age in years
/**
*
*/
export function getAge(now: Date, birthday: Date): number {
// trick to ignore year
const backToFuture = new Date(now.getTime());
backToFuture.setFullYear(birthday.getFullYear());
// 'now' and 'dateNoYear' has the same year, so it wouldn't affect the result
// check month to avoid leap year issue
const hasBirthdayThisYear = now.getMonth() >= birthday.getMonth() && backToFuture.getTime() >= birthday.getTime();
return (now.getFullYear() - birthday.getFullYear()) + (hasBirthdayThisYear ? 0 : -1);
}
/**
*
*/
describe('getAge', () => {
it('already has a birthday this year', () => {
// already has a birthday this year
expect(getAge(new Date('2020-05-08T12:00'), new Date('2010-01-01T12:00'))).toBe(10);
expect(getAge(new Date('2020-05-08T12:00'), new Date('2010-05-01T12:00'))).toBe(10);
});
it('not has a birthday this year', () => {
// not has a birthday this year
expect(getAge(new Date('2020-05-08T12:00'), new Date('2010-06-01T12:00'))).toBe(9);
expect(getAge(new Date('2020-05-08T12:00'), new Date('2010-12-01T12:00'))).toBe(9);
});
it('zero age', () => {
expect(getAge(new Date('2020-05-08T12:00'), new Date('2020-04-01T12:00'))).toBe(0);
});
it('leap year #1', () => {
expect(getAge(new Date('2021-02-28T12:00'), new Date('2020-02-29T12:00'))).toBe(0);
});
it('leap year #2', () => {
expect(getAge(new Date('2020-02-29T13:00'), new Date('2019-03-01T11:00'))).toBe(0);
});
it('leap year #3', () => {
expect(getAge(new Date('2020-02-29T13:00'), new Date('2016-03-01T11:00'))).toBe(3);
expect(getAge(new Date('2020-02-29T13:00'), new Date('2016-02-29T11:00'))).toBe(4);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment