javascript 昨日や明日の日付を取得する
- 作成日 2021.05.13
- 更新日 2022.08.24
- 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);
}
-
前の記事
gitlab WEBIDEの使い方 2021.05.13
-
次の記事
go言語 スライス(配列)内の値を別スライスに代入する 2021.05.13
コメントを書く