[removed] get all months between two dates?

后端 未结 10 614
醉酒成梦
醉酒成梦 2020-12-09 10:12

I have two date strings like this:

var startDate = \'2012-04-01\';
var endDate = \'2014-11-01\';

And I want to end up with an array of stri

10条回答
  •  感情败类
    2020-12-09 10:29

    All solutions above run in O(n^2) time complexity, which is not very efficient. See below solution in O(n) time complexity:

    function getAllMonths(start, end){	
    	let startDate = new Date(start);
    	let startYear = startDate.getFullYear();
    	let startMonth = startDate.getMonth()+1;
    	
    	let endDate = new Date(end);
    	let endYear = endDate.getFullYear();
    	let endMonth = endDate.getMonth()+1;
    	
    	let countMonth = 0;
    	let countYear = 0;
    	let finalResult = [];
    
    	for(let a=startYear; a<=endYear; a++){
    
    		if(startYear0){
    				countMonth += 12;
                }
    			countYear+=1;
    			startYear++;
            }else 
    		if(startYear==endYear){
    			countMonth+=endMonth;
            }
        }
    	for(let i=startMonth; i<=countMonth+startMonth; i++){
    		finalResult.push(startDate.getFullYear()+(Math.floor(i/12)) + "-" + Math.round(i%13) + "-" + "01");
        }
    	return finalResult;
    }
    
    getAllMonths('2016-04-01', '2018-01-01');

    Might share a much more simpler code

提交回复
热议问题