JavaScript Dateを使って明日の日付を取得するサンプル

環境
Windows 10 Home 64bit
Google Chrome 109.0.5414.120(Official Build) (64 ビット)

構文
1.ボタンのイベントの定義
document.getElementById('ボタンのID名’).onclick = function(){処理コード}
2.年月日の取得
const 変数名 = new Date()
変数名.getFullYear() //年
変数名.getMonth() //月
明日の取得
変数名.getDate() +1  //明日
3.str.padStart(targetLength [, padString])
現在の文字列の先頭に padString が適用された、指定された targetLength の長さの String です。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<input id="btnshow" type="button" value="表示"/>
<script>
document.getElementById('btnshow').onclick = function(){
const now = new Date()
//昨日の日付
let yday = new Date(now.getFullYear(), now.getMonth(), now.getDate() +1 );
yday = `${yday.getFullYear()}-${(yday.getMonth() + 1).toString().padStart(2, '0')}-${yday.getDate().toString().padStart(2, '0')}`.replace(/\n|\r/g, '');
alert(yday);
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <input id="btnshow" type="button" value="表示"/> <script> document.getElementById('btnshow').onclick = function(){ const now = new Date() //昨日の日付 let yday = new Date(now.getFullYear(), now.getMonth(), now.getDate() +1 ); yday = `${yday.getFullYear()}-${(yday.getMonth() + 1).toString().padStart(2, '0')}-${yday.getDate().toString().padStart(2, '0')}`.replace(/\n|\r/g, ''); alert(yday); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<input id="btnshow" type="button" value="表示"/>

<script>
document.getElementById('btnshow').onclick = function(){
  
  const now = new Date()      
  //昨日の日付
   let yday = new Date(now.getFullYear(), now.getMonth(), now.getDate() +1 );

  yday = `${yday.getFullYear()}-${(yday.getMonth() + 1).toString().padStart(2, '0')}-${yday.getDate().toString().padStart(2, '0')}`.replace(/\n|\r/g, '');
 alert(yday);

}
</script>

</body>
</html>

実行結果
「表示」ボタンを押すと、明日の日付2023-02-08が表示されます。

IT

Posted by arkgame