Skip to content

Instantly share code, notes, and snippets.

@onori
Created January 7, 2023 04:02
Show Gist options
  • Save onori/b5349abb637b9986908b73a8a4501049 to your computer and use it in GitHub Desktop.
Save onori/b5349abb637b9986908b73a8a4501049 to your computer and use it in GitHub Desktop.
export const calculateAge = (
  dateOfBirth: Date,
  referenceDate: Date = new Date()
) => {
  const referenceYear = referenceDate.getFullYear()
  const referenceMonth = referenceDate.getMonth()
  const referenceDay = referenceDate.getDate()

  const birthYear = dateOfBirth.getFullYear()
  const birthMonth = dateOfBirth.getMonth()
  const birthDay = dateOfBirth.getDate()

  const age = referenceYear - birthYear

  if (
    referenceMonth < birthMonth ||
    (referenceMonth === birthMonth && referenceDay < birthDay)
  ) {
    return age - 1
  } else {
    return age
  }
}

テスト

import { assertEquals } from 'https://deno.land/std@0.65.0/testing/asserts.ts'

import { calculateAge } from './calc_age.ts'
Deno.test('calculateAge', () => {
  // 2023/01/01
  const referenceDate = new Date(2023, 0, 1)

  // 1990/01/01 = 33歳
  const dateOfBirth1 = new Date(1990, 0, 1)
  assertEquals(calculateAge(dateOfBirth1, referenceDate), 33)

  // 1990/03/01 = 32歳
  const dateOfBirth2 = new Date(1990, 2, 1)
  assertEquals(calculateAge(dateOfBirth2, referenceDate), 32)

  // 1990/12/31 = 32歳
  const dateOfBirth3 = new Date(1990, 11, 31)
  assertEquals(calculateAge(dateOfBirth3, referenceDate), 32)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment