Skip to content

Instantly share code, notes, and snippets.

@forrestgrant
Created December 4, 2025 15:16
Show Gist options
  • Select an option

  • Save forrestgrant/fcf50c971cecfb7106f94e40e70f9d81 to your computer and use it in GitHub Desktop.

Select an option

Save forrestgrant/fcf50c971cecfb7106f94e40e70f9d81 to your computer and use it in GitHub Desktop.
function age(date: string): number { // readonly line
const [y, m, d] = date.split("-").map(Number);
const birth = new Date(y, m - 1, d); // local date, no timezone issues
const today = new Date();
let age = today.getFullYear() - birth.getFullYear();
// If birthday hasn't happened yet this year, subtract 1
if (
today.getMonth() < birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate())
) {
age--;
}
return age;
}
describe('age function', () => {
test('input date is 18 years ago yesterday => should be 18', () => {
const now = new Date();
const todayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const yesterdayUTC = new Date(todayUTC);
yesterdayUTC.setUTCDate(todayUTC.getUTCDate() - 1);
const eighteenYearsAgoYesterday = new Date(yesterdayUTC);
eighteenYearsAgoYesterday.setUTCFullYear(yesterdayUTC.getUTCFullYear() - 18);
const result = age(eighteenYearsAgoYesterday.toISOString().split('T')[0]);
expect(result).toBe(18);
});
test('input date is 18 years ago + 1 day => should be 17 (1 day shy of 18th birthday)', () => {
const now = new Date();
const todayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const oneDayFromNowUTC = new Date(todayUTC);
oneDayFromNowUTC.setUTCDate(todayUTC.getUTCDate() + 1);
const eighteenYearsAgoPlus1Day = new Date(oneDayFromNowUTC);
eighteenYearsAgoPlus1Day.setUTCFullYear(oneDayFromNowUTC.getUTCFullYear() - 18);
const result = age(eighteenYearsAgoPlus1Day.toISOString().split('T')[0]);
expect(result).toBe(17);
});
test('input date is 18 years ago today => should be 18', () => {
const now = new Date();
const todayUTC = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const eighteenYearsAgoToday = new Date(todayUTC);
eighteenYearsAgoToday.setUTCFullYear(todayUTC.getUTCFullYear() - 18);
const result = age(eighteenYearsAgoToday.toISOString().split('T')[0]);
expect(result).toBe(18);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment