Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the month and year from the past date untill now JavaScript

I'm trying to figure out how to get combinations of year and month from the past date up till now.

So lets say, the past date is given as

const date = "December 2019"

Then I need an array

const arrayOfMonths = [ "April 2020", "March 2020", "February 2020", "January 2020", "December 2019"]
like image 647
Yukichka Avatar asked Dec 09 '25 16:12

Yukichka


2 Answers

You can use JavaScript Date objects and a while loop.

Just subtract a month from the current month till you get to the date you want.

Something like this should work.

https://jsfiddle.net/wsf61jpk/5/

var date="December 2018";
var result=[];

//set both start and end date to first date of the month
const end_date = new Date(date.replace(" ", " ,1 "));
const start_date = new Date(new Date().getFullYear(), new Date().getMonth(), 1);


while(end_date<=start_date){

result.push(start_date.toLocaleString('default', { month: 'long' , year: 'numeric'}));
start_date.setMonth(start_date.getMonth() - 1);

}

console.log(result);
like image 91
George Pant Avatar answered Dec 11 '25 06:12

George Pant


i did it using by leveraging the javascript date functions

var oldDate = "December 2019";
var old = new Date(Date.parse(oldDate));
var today = new Date();
var yearsCount= today.getFullYear() - old.getFullYear();
var monthsArr = [];
for(var i = 0; i<=yearsCount;i++){
for(var j = 0; j<12;j++){
//skipping the months before the month in old date and the after the month in the current day
if(i==0 && j<old.getMonth()) continue;
if(i==yearsCount && j>today.getMonth()) continue;
// creating a new date in the format : mm-dd-yyyy (with dd=01) 
var newDate = new Date((j+1)+"-01-"+(old.getFullYear()+i))
//using to localestring to transfrom the date created into format : month year
var newmonth = newDate.toLocaleString('default', { month: 'long',year:'numeric' });
//pushing to the array
monthsArr.push(newmonth);
}
}
console.log(monthsArr);

there is a room for improvement but it gets the job done

like image 36
Moussaabmma Avatar answered Dec 11 '25 05:12

Moussaabmma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!