
Javascriptで日付の絡んだ集計処理などを行う時に対象月の月末を自動計算して、日付フォーマットの配列で一覧を返してくれる関数を作りました。
ソースコード
function get_ym2ymd_array(ym){
const arr = []
if(!ym){return arr}
const [y , m] = ym.split("-")
const dt = new Date(`${y}-${m}-01`)
const enf_of_month = new Date(dt.setMonth(dt.getMonth()+1, 0)).getDate()
for(let i=1; i<=enf_of_month; i++){
const d = ("0" + String(i)).slice(-2)
arr.push(`${y}-${m}-${d}`)
}
return arr
}
使い方
get_ym2ymd_array("2023-10")
関数に対して、年と月を上記のフォーマットで送ることで、その月の1日から末日までの日付フォーマットを配列で取得できます。
解説
仕組みは単純で、送られてきた年月の1日を指定して、まずdateインスタンスを作ります。
const dt = new Date(`${y}-${m}-01`)
そこから、翌月の0日を指定すると、前月の末日が取得できます。
const enf_of_month = new Date(dt.setMonth(dt.getMonth()+1, 0)).getDate()
最後に、1日から最終日までをfor文で処理して、配列を作成します。
for(let i=1; i<=enf_of_month; i++){
const d = ("0" + String(i)).slice(-2)
arr.push(`${y}-${m}-${d}`)
}
デモ
今月の年月日一覧