1. Home
  2. Archive
  3. 年齢と誕生日の変換プログラム[PHP]

年齢と誕生日の変換プログラム[PHP]

PHPで年齢を引数にして誕生日を返す関数とその逆の関数のサンプルです。結構使いどころが多いんですよね、最近。というわけでメモっておこうと思います。

function get_age($birth){
  $ty = date("Y");
  $tm = date("m");
  $td = date("d");
  list($by, $bm, $bd) = explode('-', $birth);
  $age = $ty - $by;
  if($tm * 100 + $td < $bm * 100 + $bd) $age--;
  return $age;
}

function get_birthday($age){
  $ty = date("Y");
  $tm = date("m");
  $td = date("d");
  $by = $ty - $age;
  $birth['under'] = date("Y-m-d",mktime(0,0,0,$tm,$td+1,$by-1));
  $birth['over'] = date("Y-m-d",mktime(0,0,0,$tm,$td,$by));
  return $birth;
}

誕生日から年齢を返す方は、誕生日はYYYY-mm-ddの形式での入力のみです。いろいろな形式にも対応するようにすればもっと使いやすくなると思います。

年齢から誕生日を返す方の返り値は配列です。$birth[’under’]~$birth[’over’]の間に誕生日があるということになります。配列の中の値はYYYY-mm-ddの形です。下記、実行サンプルになります。

<?php
//誕生日→年齢
$birthday = "1984-01-08";
$res_age = get_age($birthday);
echo "<p>あなたは{$res_age}歳だ!</p>";

//年齢→誕生日
$age = 23;
$res_birthday = get_birthday($age);
echo "<p>あなたの誕生日は {$res_birthday['under']} ~ {$res_birthday['over']} の間です。</p>";
?>
[出力]
あなたは23歳だ!

あなたの誕生日は 1983-04-04 ~ 1984-04-03 の間です。

いずれの関数も実行した日付が基準となります。上記サンプルは2007年4月3日時点での出力結果です。

コメントフォーム

※HTMLタグは使用できません。