阵列与使用天数 [英] Array with number of days using moment

查看:88
本文介绍了阵列与使用天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个数组,其中包含两个日期之间的天数.

I am trying to create an array with number of days between two dates.

日期可以是任何日期,但我在此示例中使用以下内容.

The dates can be anything but i am using the following for this example.

Start : 11/30/2018, End: 09/30/2019
Array= [30,31,29,30....31]

我要做什么:

此处的日期范围为30 to 3030-29.

我有以下代码:

const start = "11/30/2018";
const end = "09/30/2019";

const dates = [];

const mstart = moment(new Date(start));
const mend = moment(new Date(end));

for (let i = 0; mstart < mend ; i++) {

    const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : -1);
                      //mstart.daysInMonth() + (i === 0 ? -1 : 0) for the first case.

    dates.push(daysInMonth);

    mstart.add(1, 'M');
}

console.log(dates);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

问题:

该日期范围可用于其他日期,只要它不在月底即可.

The date range works for other dates as long as it's not towards the end of the month.

我需要从开始日期到结束日期的日期范围.在这里,它会计算30到29之间的日期,但是一旦到2月,则需要该月的28号,然后从该日期开始计算日期范围.

I need the date range to go from start date to end date. Here, it calculates the date from 30 to 29 but as soon as it goes to February it takes 28th of that month and then starts the date range from there.

我该如何解决?

推荐答案

我将直接比较日期而不是按月中的天数进行比较.还添加了支票,以确保您正确地捕获了结束日期(如果开始日期和结束日期不是同一天)

I would go about comparing the dates directly rather than by the number of days in the month. Also added in a check to make sure you capture your enddate correctly if its not the same day for start and end

const start = "11/30/2018";
const end = "09/30/2019";

const dates = [];

const mstart = moment(new Date(start));
const mend = moment(new Date(end));

let i = 0;
while (1 == 1) {
  let nextStart = mstart.clone().add(i, 'M');
  let nextEnd = mstart.clone().add(i + 1, 'M') > mend ? mend : mstart.clone().add(i + 1, 'M');

  dates.push(nextEnd.diff(nextStart, 'days'));

  if (nextEnd >= mend) {
    break;
  }

  i += 1
}


console.log(dates);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

这篇关于阵列与使用天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆