从一个月开始

发布于 2025-01-24 19:53:53 字数 539 浏览 3 评论 0原文

我希望从本月开始的整个天数。例如,本月(2022年4月)有

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())

30

//  [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]

的第一天或第一个月,但是如何从上面的示例中获得想要的结果,

因此,如果我获取当前月份,则基本上mist将自动生成此数组。我们该如何实现?

I wish to have all the days from the current month in an array. For example this month (April 2022) has 30 days so I wish to have an array of integers like so:

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 ]

My attempt :

Array.from(Array(moment('2022-04').daysInMonth()).keys())

And the output is :

//  [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]

I have and idea how moment works and 0 is always the first day or the first month , but how can i achieve the result that i want from the example above

So basically moment will generate automatically this array if I fetch the current month. How can we achieve that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开柳相依 2025-01-31 19:53:53
  1. 创建Moment对象
  2. 设置所需月的月份
  3. 使用 daysInmonth() 获取天数
  4. 创建一个从1到步骤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>

  1. Create moment object
  2. Set the month to the desired month
  3. Use daysInMonth() to get the number of days
  4. 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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文