簡體   English   中英

使用 moment.js 獲取當月的天數

[英]Using moment.js to get number of days in current month

如何使用 moment.js 獲取當月的天數? 最好沒有臨時變量。

Moment 有一個daysInMonth函數

月中的天數1.5.0+

 moment().daysInMonth();

獲取當月的天數。

 moment("2012-02", "YYYY-MM").daysInMonth() // 29 moment("2012-01", "YYYY-MM").daysInMonth() // 31

您可以在數組中獲取天數

Array.from(Array(moment('2020-02').daysInMonth()).keys())
//=> [0, 1, 2, 3, 4, 5...27, 28]

Array.from(Array(moment('2020-02').daysInMonth()), (_, i) => i + 1)
//=> [1, 2, 3, 4, 5...28, 29]

要在數組中返回天數,您還可以使用

Array.from({length: moment('2020-02').daysInMonth()}, (x, i) => moment().startOf('month').add(i, 'days').format('DD')

// ["01","02","03" ... "28","29"]

MomentJS 可以列出月份中的天數。

 const daysofThisMonth = Array.from(Array(moment().daysInMonth()), (_, i) => i + 1); console.log(daysofThisMonth);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM