JavaScriptで月末日を取得する

JavaScriptで指定した月の最後の日を取得する方法をメモ。

サンプルコード

new Date()の引数を指定する際に、月の値を翌月、日の値を0とすることで、指定した前月の最後の日を取得できます。

const year = 2024;
const month = 2;

const startDate = new Date(year, month - 1, 1);
const endDate = new Date(year, month, 0);

console.log('startDate:', startDate); // startDate: Thu Feb 01 2024 00:00:00 GMT+0900 (日本標準時)
console.log('endDate:', endDate); // endDate: Thu Feb 29 2024 00:00:00 GMT+0900 (日本標準時)

2024年2月のデモページ

new Date()の月の値は0~11になりますが、12月の最後の日を取得したい場合は月に12を指定したので問題ないようです。

const year = 2024;
const month = 12;

const startDate = new Date(year, month - 1, 1);
const endDate = new Date(year, month, 0); // 年月が2024年13月の指定
const endDate2 = new Date(2025, 0, 0); // 年月が2025年1月の指定

console.log('startDate:', startDate); // startDate: Sun Dec 01 2024 00:00:00 GMT+0900 (日本標準時)
console.log('endDate:', endDate); // endDate: Tue Dec 31 2024 00:00:00 GMT+0900 (日本標準時)
console.log('endDate2:', endDate2); // endDate2: Tue Dec 31 2024 00:00:00 GMT+0900 (日本標準時)

2024年12月のデモページ

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930