从一个月中获取所有天数
Get all days from a month
我希望将当前月份的所有日期都放在一个数组中。例如这个月(2022 年 4 月)有 30 天,所以我希望有一个整数数组,如下所示:
const monthDays = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 , 30 ]
我的尝试:
Array.from(Array(moment('2022-04').daysInMonth()).keys())
输出为:
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
我知道时刻是如何工作的,0
总是第一天或第一个月,但是我怎样才能从上面的例子中得到我想要的结果
所以基本上 moment
会在我获取当前月份时自动生成这个数组。我们怎样才能做到这一点?
- 创建时刻对象
- 将月份设置为所需的月份
- 使用
daysInMonth()
得到天数
- Create an array from
1
to the result of step 3
const mom = new moment();
mom.set('month', 3); // 0-indexed, so 3 --> 4 --> April
const daysInApril = mom.daysInMonth();
const aprilDays = Array.from({length: daysInApril}, (_, i) => i + 1);
console.log(aprilDays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
我希望将当前月份的所有日期都放在一个数组中。例如这个月(2022 年 4 月)有 30 天,所以我希望有一个整数数组,如下所示:
const monthDays = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 , 30 ]
我的尝试:
Array.from(Array(moment('2022-04').daysInMonth()).keys())
输出为:
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
我知道时刻是如何工作的,0
总是第一天或第一个月,但是我怎样才能从上面的例子中得到我想要的结果
所以基本上 moment
会在我获取当前月份时自动生成这个数组。我们怎样才能做到这一点?
- 创建时刻对象
- 将月份设置为所需的月份
- 使用
daysInMonth()
得到天数 - Create an array from
1
to the result of step 3
const mom = new moment();
mom.set('month', 3); // 0-indexed, so 3 --> 4 --> April
const daysInApril = mom.daysInMonth();
const aprilDays = Array.from({length: daysInApril}, (_, i) => i + 1);
console.log(aprilDays);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>