简体   繁体   中英

Get all list of month and year from given date to current date

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 ie January to current month ie April? If any one needs any further information please do let me know.

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)

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