LoginSignup
47
29

More than 5 years have passed since last update.

JavaScriptで生年月日から年齢を計算する簡単ロジック

Last updated at Posted at 2017-03-09

昔のFlashのTipsをJavaScript(ECMAScript 2017)で書き直しました。

ロジック

年齢 = floor((今日-誕生日)/10000)で計算できる

サンプルコード

// あなたの誕生日
const yourBirthDay = {
  year: 1983,
  month: 2,
  date: 15
};

// Dateインスタンスに変換
const birthDate = new Date(yourBirthDay.year, yourBirthDay.month - 1, yourBirthDay.date);

// 文字列に分解
const y2 = birthDate.getFullYear().toString().padStart(4, '0');
const m2 = (birthDate.getMonth() + 1).toString().padStart(2, '0');
const d2 = birthDate.getDate().toString().padStart(2, '0');

// 今日の日付
const today = new Date();
const y1 = today.getFullYear().toString().padStart(4, '0');
const m1 = (today.getMonth() + 1).toString().padStart(2, '0');
const d1 = today.getDate().toString().padStart(2, '0');

// 引き算
const age = Math.floor((Number(y1 + m1 + d1) - Number(y2 + m2 + d2)) / 10000);
console.log(age);

※ES2017水準のJavaScriptで書いているので、IE11では動作しません。IE11向けに動作させるには、Babel(Polyfill)を利用くださいませ。Babelの使い方は記事「最新版で学ぶwebpack 4入門 - BabelでES2017環境の構築 - ICS MEDIA」が参考になります。

サンプルはこちら

image.png

 参考記事

47
29
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
29