LoginSignup
3

More than 1 year has passed since last update.

生年月日から年齢を計算して表示 JS PHP

Last updated at Posted at 2020-08-20

プロフィールに年齢を表記することがあったのでメモ

PHPで年齢を計算して表示

"19910402"の部分を変更

php
年齢は<?php echo floor((date('Y/m/d') - 19910402) / 10000); ?>歳です。

JavaScriptで年齢を計算して表示

"19910402"の部分を変更

html
年齢は<span id="age"></span>歳です。
javascript
function calcAge(birthdate) {
	const today = new Date();
	targetdate = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate();
	return (Math.floor((targetdate - birthdate) / 10000));
}
document.getElementById("age").innerHTML = calcAge(19910402);

まとめ

現在の日付から生年月日を引いて、1万で割ると年齢が出るらしいです。数学不思議。

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
3