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();
new Date(now.getFullYear(), now.getMonth(), now.getDate() – 1)
使用例
<!DOCTYPE html>
<html>
<body>
<input id="btnshow" type="button" value="表示"/>
<script>
document.getElementById('btnshow').onclick = function(){
const now = new Date()
//昨日の日付
alert(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<input id="btnshow" type="button" value="表示"/>
<script>
document.getElementById('btnshow').onclick = function(){
const now = new Date()
//昨日の日付
alert(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <input id="btnshow" type="button" value="表示"/> <script> document.getElementById('btnshow').onclick = function(){ const now = new Date() //昨日の日付 alert(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)); } </script> </body> </html>
実行結果
「表示」ボタンを押すと、昨日の日付が表示されます。