Skip to content

Instantly share code, notes, and snippets.

@t0kio2
Created October 23, 2024 15:49
Show Gist options
  • Save t0kio2/9e70e891cf3aff6a3fc1e5128a760b35 to your computer and use it in GitHub Desktop.
Save t0kio2/9e70e891cf3aff6a3fc1e5128a760b35 to your computer and use it in GitHub Desktop.
const calculateAge = (birthdayStr: string) => {
if (!birthdayStr) return
const birthday = new Date(birthdayStr)
const today = new Date()
let age = today.getFullYear() - birthday.getFullYear()
const monthDiff = today.getMonth() - birthday.getMonth()
// 誕生日が来ていない場合、年齢から1引く
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthday.getDate())) {
age--
}
return age
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment