【问题标题】:Looping through each month between two years两年之间的每个月循环
【发布时间】:2020-07-22 10:01:00
【问题描述】:

我的 javascript 很糟糕,我是 C# 开发人员,但我们到了。所以我需要在开始年份和月份到结束年份和月份之间的每个月循环。

startMonth 和 startYear 将始终分别为 1 和 2010。

我目前有以下解决方案:

//Get the current year and month
let currentTime = new Date();
let currentYear = currentTime.getFullYear();
let currentMonth = currentTime.getMonth() + 1;

//Set starting year and month
let startYear = 2010;
let startMonth = 1;

//Loop through the years and months
for (let i = startYear; i <= currentYear; i++){
    if (i === currentYear ){
        for (let k = 1; k <= currentMonth; k++){
            //Do work
        }
    } else {
        for (let j = startMonth; j <= 12; j++){
            //Do work
        }
    }
} 

有人有更好的解决方案吗?我觉得这真的很笨拙。我不介意使用第三方软件包,所以如果片刻或其他东西可以使用,那么我会使用它。

【问题讨论】:

标签: javascript node.js


【解决方案1】:

这就是你想要的:

const start = moment.utc('2018-12');

const end = moment.utc('2020-02');

const year = end.diff(start, 'years');
const month = end.diff(start, 'months')

console.log(start, end);
console.log(year, month);// 1 14
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    首先,请注意从011 的月份,所以一月是0 而不是1

    JavaScript 的 Date 类自动处理“溢出”。例如日期

    new Date(2010, 12, 1)
    

    自动变为“2011 年 1 月 1 日”。

    这可以用来简单地增加日期的月份:

    const currentDate = new Date(2010, 0, 1);
    const endDate = new Date();
    endMonth.setMonth(endMonth.getMonth() + 1);
    
    while (currentDate.getFullYear() != endMonth.getFullYear() && currentDate.getMonth() != endMonth.getMonth()) {
      // Do something 
      currentDate.setMonth(currentDate.getMonth() + 1);
    }
    

    (请注意,如果开始日期已经在结束日期之后,可能会导致无限循环。)

    【讨论】:

      【解决方案3】:

      这里是在不添加第三方库的情况下略有改进:

      //Get the current year and month
      let currentTime = new Date();
      let currentYear = currentTime.getFullYear();
      let currentMonth = currentTime.getMonth() + 1;
      
      //Set starting year and month
      let startYear = 2010;
      let startMonth = 1;
      
      //Loop through the years and months
      for (let i = startYear; i <= currentYear; i++){
         for (let j = startMonth; j <= (i == currentYear ? currentMonth: 12); j++){
           //Do work
         }
      } 
      

      【讨论】:

        猜你喜欢
        • 2020-12-08
        • 2020-08-13
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多