LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptで年齢計算機能を作ってみた

Posted at

JavaScriptの標準ライブラリのDateを利用して年齢を計算する機能を作成してみました。

コード

age.html
<div id="text-button">
    <p id="countAge">年齢</p>
</div>
age.css
#text-button {
    display: block;
    cursor: pointer;
    width: 500px;
    text-align: center;
    border: 1px solid #232323;
  }
age.js
function countage(){
    const today = new Date();
    const birth = new Date(1997, 01, 01);


    const birthYear = 1997;
    const birthMonth = 2;
    const birthDay = 1;

    let nowYear = today.getFullYear();
    let nowMonth = today.getMonth() + 1;
    let nowDay = today.getDate();
    const nowHours = today.getHours();
    const nowMinutes = today.getMinutes();
    const nowSeconds = today.getSeconds();

    if(nowMonth === 1){
        nowMonth = 13;
        nowYear -= 1;
    };

    count = (`私が誕生してから${nowYear - birthYear}${nowMonth - birthMonth}ヶ月${nowDay - birthDay}${nowHours}時間${nowMinutes}${nowSeconds}秒経ちました!`);

    document.getElementById("text-button").onclick = function(){
    document.getElementById("countAge").innerHTML = count;
    };
};
setInterval("countage();",1000);

結果

こちらを実行するとサイト上に「年齢」という欄が出てくるので、この文字をクリックすると「私が誕生してから○○経ちました。」とちゃんと表示されました。
クリックするたびに更新もしてくれます。

課題点

日付間の計算をプログラムする時に一番気をつけなければならないのは、「月」です。
例えば1月1日と2月5日の間は「1ヶ月と4日」なので純粋に引き算すれば大丈夫です。
一方1月6日と2月5日の間は「0ヶ月と30日」となるので複雑になります。
この部分で躓き、どのような数字にも当てはまるようなプログラムは書けなかったので、今後勉強していきたいです。

0
0
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
0
0