LoginSignup
1
2

More than 5 years have passed since last update.

JavaScript 日付計算

Posted at

js.png

JavaScript勉強メモ。

4点を意識して写経なり
- 動くアプリを作る
- 書いたコードを理解
- 機能またはデザインを追加
- 成果物は、ネット上にあげる

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>日付計算</title>
</head>
<body>
    <h1>日付計算の練習</h1>
    <p>誕生日<input type="text" id="birthday" value="1984-12-05"></p>
    <p><input type="button" value="計算!" onclick="getAge()";></p>
    <p>生まれてから<span id="dayPast">???</span>日経過していて、だいたい<span id = age>???</span>です。</p>

    <script>
        function getAge(){
            //入力値の取得
            var birthday = document.getElementById("birthday").value.split("-");;

            //日付オブジェクトの作成(配列に値を入れる)
            var d1 = new Date(birthday[0], birthday[1]-1, birthday[2]);
            var d2 = new Date();

            //日数、年齢の計算(日付:現在から生まれた年を引く)
            var diff = d2.getTime() - d1.getTime();
            var dayPast = Math.floor(diff/(1000*60*60*24));
            var age = Math.floor(dayPast / 365.25);

            //結果の表示
            document.getElementById("dayPast").innerHTML = dayPast;
            document.getElementById("age").innerHTML = age;        
        }
    </script>

</body>
</html>
1
2
0

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
1
2