简体   繁体   中英

Looping through each month between two years

My javascript is horrible, I am a C# dev but here we are. So I need to loop through every month between a start year and month to an end year and month.

The startMonth and startYear will always be 1 and 2010 respectively.

I have the following solution at the moment:

//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
        }
    }
} 

Does someone have a better solution? I feel like this is really clunky. I don't mind using third party packages so if moment or something will work then I'll use it.

Here is what you want:

 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
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

First off, be aware that months run from 0 to 11 so January is 0 not 1 !

JavaScript's Date class automatically handles "overflows". So for example a date

new Date(2010, 12, 1)

automatically becomes "January 1st, 2011 ".

This can be used to simply increment just the month of a date:

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);
}

(Watch out that is could result in an endless loop if the start date is already after the end date.)

Here is a slight improvement without adding a third party library:

//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
   }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM