Reputation: 861
Suppose I have variable with datetime as,
let givenDateTime = '2021-01-29T04:22:22.148Z';
I want to get all months and year in an array from givenDateTime to currentDate.
Expected O/P : ["April 2021", "March 2021", "February 2021", "January 2021"]
For this I tried as:
let createdDate = new Date(givenDateTime);
let currentDate = new Date();
let dateAndYearList = [createdDate.toLocaleString('en', { month: 'long', year: 'numeric' })];
while (createdDate.setMonth(createdDate.getMonth() + 1) < currentDate) {
dateAndYearList.unshift(createdDate.toLocaleString('en', { month: 'long', year: 'numeric'
}));
}
But on console.log(dateAndYearList) , it gives , ** ["April 2021", "March 2021","January 2021"]**, all month from January except for February.
Can anybody tell me how can I get all the months from created month i.e. January to current month i.e. April? If any one needs any further information please do let me know.
Upvotes: 1
Views: 2380
Reputation: 380
set the day of createdDate
to 1
let givenDateTime = '2021-01-29T04:22:22.148Z';
let createdDate = new Date(givenDateTime);
createdDate.setDate(1);
let currentDate = new Date();
let dateAndYearList = [createdDate.toLocaleString('en', { month: 'long', year: 'numeric' })];
while (createdDate.setMonth(createdDate.getMonth() + 1) < currentDate) {
dateAndYearList.unshift(createdDate.toLocaleString('en', { month: 'long', year: 'numeric'
}));
}
console.log(dateAndYearList)
Upvotes: 1