TransWikia.com

Looping through each month between two years

Stack Overflow Asked on November 22, 2021

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.

3 Answers

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

Answered by RoToRa on November 22, 2021

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

Answered by crosen9999 on November 22, 2021

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>

Answered by 8HoLoN on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP