JavaScript 昨日のフォーマット日付を取得するサンプル

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

構文
1.ボタンのイベントの定義
document.getElementById('ボタンのID名’).onclick = function(){処理コード}
2.年月日の取得

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const 変数名 = new Date()
変数名.getFullYear() //年
変数名.getMonth() //月
変数名.getDate()  //日
const 変数名 = new Date() 変数名.getFullYear() //年 変数名.getMonth() //月 変数名.getDate()  //日
const 変数名 = new Date()
変数名.getFullYear() //年
変数名.getMonth() //月
変数名.getDate()  //日

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-06が表示されます。

JavaScript

Posted by arkgame