javascript 昨日や明日の日付を取得する

javascript 昨日や明日の日付を取得する

javascriptで昨日や明日の日付を取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

昨日の日付を取得

「now.getDate() – 1」することで昨日の日付は取得することが可能です。

<input id="btn" type="button" value="ボタン"/>

<script>

'use strict';

document.getElementById('btn').onclick = function(){
  
  const now = new Date()      
  //昨日
  console.log(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1));

}

</script>

実行結果

フォーマットを変更する場合は、以下のようにテンプレートリテラルを使用すれば可能です。

'use strict';

document.getElementById('btn').onclick = function () {

  const now = new Date()
  //昨日
  let yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);

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

  console.log(yesterday);

}

実行結果

明日の場合は「+1」します。

'use strict';

document.getElementById('btn').onclick = function () {

  const now = new Date()
  //明日
  let yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

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

  console.log(yesterday);

}

実行結果

コードの簡潔化

また、以下のコードを、

document.getElementById('btn').onclick = function () {

  const now = new Date()
  //明日
  let yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

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

  console.log(yesterday);

}

アロー関数とdocument.getElementByIdを省略して、簡潔に記述することもできます。

btn.onclick = () => {

  const now = new Date()
  //昨日
  let yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);

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

  console.log(yesterday);

}