金曜日, 6月 16, 2023

Let's start JavaScript 09 
シンプルに年齢を計算する

シンプルに年齢を計算してみます。
 
HTMLの基本は入力と表示設定。
<!-- index.html -->

<!DOCTYPE html>
<html>
<head>
<title>年齢を計算する</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="links/rule.css">
</head>
<body>
<h4>&emsp;&emsp;&emsp;</h4>
<br>
<h5>[年]を選択・入力後はカーソルキーで[月・日]へ移動
    </h5>
<label for="birthDate">生年月日:</label>
<input type="date" id="birthDate">
<button onclick="CalculateAge()">
                &emsp;計算する&emsp;</button>
<h3><br>
<p id="result"></p>
<script src="links/action.js"></script>
</h3>
</body>
</html>

<!-- index.html -->

JavaScriptは1970年がポイントです
/* action.js */

function CalculateAge() {
var BirthDate = new Date(document.getElementById
("birthDate").value);
/* HTMLで宣言するCalculateAgeの設定。
 document.getElementByIdは
 プロパティが指定された文字列に
 一致する要素を表すBirthDateオブジェクトを返す*/ 
var NowAge = Date.now() - BirthDate.getTime();
/* NowAgeに現在の日付から誕生日を引いた値を入れる */
var AgeDate = new Date(NowAge);
/* 年齢はNowAge */
var age = Math.abs(AgeDate.getUTCFullYear() - 1970);
document.getElementById("result").innerHTML =
"現在の年齢は " + age + " 歳です";
/* .getUTCFullYear() - 1970で、指定された日時を協定世界時(UTC()(の1970年1月1日 00:00:00 からの経過ミリ秒単位の数値で返す。それ以前の時刻は負の数を返す。*/
/* action.js */

CSSはお決まり設定
/* rule.css */
@charset "UTF-8";
* {
margin: 0px;
padding: 0px;
}

html
{
overflow-y:scroll;
}

body *, ::before, ::after {
box-sizing: border-box;
}

.clearfix::after {
content: " ";
display: block;
clear: both;
}

body {
color: #000000;
background-color: #b9d08b;
text-align: center;
font-size: 100%;
line-height: 1.7;
-webkit-text-size-adjust: 100%;
}

h3 {
color: #007b43;
font-weight: Bold;
font-size: 100%;
}

h4 {
color: #000000;
font-weight: normal;
font-size: 100%;
}

h5 {
color: #000000;
font-weight: normal;
font-size: 100%;
}

/* rule.css */

実行直後の画面











誕生日を入力して[計算する]ボタンで年齢が表示されます。チョット入力がもたつきますが・・・(^o^)