javascript 日付の差を計算する
- 2020.09.12
- javascript
- javascript

javascriptで、dateオブジェクトを使って、日付の差を計算するサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
日付差分計算
dateオブジェクトを使って、計算します。
1 2 3 4 5 6 7 8 9 |
// 日付を設定 var date1 = new Date("2020/05/11"); var date2 = new Date("2020/05/01"); // ミリ秒で結果が戻るの1日分のミリ秒で割る var result = (date1 - date2) / 86400000; console.log(date1 - date2); // 864000000 console.log(result); // 10 |
サンプルコード
以下は、
「計算」ボタンをクリックして、フォームから取得した日付を差分を計算して表示する
サンプルコードとなります。
※cssには「bootstrap material」を使用してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>mebeeサンプル</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons"> <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous"> </head> <style> .main { margin: 0 auto; margin-top: 200px; display: flex; flex-direction: column; align-items: center; font-size: 25px; width: 500px; } </style> <script> function hoge() { // フォームの入力を取得 var date1 = document.getElementById('date1').value; var date2 = document.getElementById('date2').value; // date型に変換 date1 = new Date(date1); date2 = new Date(date2); // 計算 86400000ミリ秒(1日) var result = (date1 - date2) / 86400000; // 表示用要素取得 var obj = document.getElementsByClassName("badge")[0]; // 結果表示 obj.textContent = result; } </script> <body> <div class="main"> <h2><span class="badge badge-primary">計算結果(日付1 - 日付2)</span></h2> <form> <div class="form-group"> <label class="bmd-label-floating">日付1</label> <input type="date" id="date1"> </div> <div class="form-group"> <label class="bmd-label-floating">日付2</label> <input type="date" id="date2"> </div> </form> <button type="button" onclick="hoge()" class="btn btn-raised btn-primary"> 計算 </button> </div> </body> </html> |
日付の差分が計算されていることが確認できます。

-
前の記事
windows ディスクトップに白い枠が残って消えない 2020.09.12
-
次の記事
php fzaninotto/fakerを利用してダミーデータを作成する 2020.09.12
コメントを書く