LoginSignup
26
27

More than 5 years have passed since last update.

Javascriptで誕生日から現在の年齢を算出

Posted at

どこかのサイトを見たんですが忘れてしまったのでメモ

birthday.js

function calculateAge(birthday) {
    var  birth = birthday.split('/'); // birth[2]: year, birth[0]: month, birth[1]: day
    var _birth = parseInt("" + birth[2] + birth[0] + birth[1]);// 文字列型に明示変換後にparseInt
    var  today = new Date();
    var _today = parseInt("" + today.getFullYear() + affixZero(today.getMonth() + 1) + affixZero(today.getDate()));// 文字列型に明示変換後にparseInt
    return parseInt((_today - _birth) / 10000);
}

function affixZero(int) {
    if (int < 10) int = "0" + int;
    return "" + int;
}

var birthday = calculateAge('01/01/1989');

この月/日/年の形式はFacebook認証アプリを作成した際に認証をして値を受け取った際にこの形式だったので書いています。

26
27
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
26
27