简体   繁体   中英

Get all the months and year from provided ISO Date to current month and year

Suppose I have ISO Date inside an object as:

const dataCreated = {"readDetail":'2020-09-17 14:23:26.978Z'}

Is it possible to I get all date from created date till todays date.

Expected O/P ->assunming current date is jan 2021 :

['2020-09-17','2020-10-17','2020-11-17','2020-12-17','2021-01-17']

I tried different searches but was unable to get find anything related to it. If anyone has any solution or in someway can guide me that would be really helpful. If any further information needed please let me know.

What you want to do is just fill your array while looping over the dates. And with each loop add one month to your original date. Note that you have to to create a new Instance of Date before saving it in your array since JavaScript saves references.

    function getDates() {
        var date = new Date("2020-09-17 14:23:26.978Z");
        var now = new Date();
    
        var datearray = [new Date(date)];
    
        while(date.setMonth(date.getMonth() + 1) < now) {
            datearray.push(new Date(date));
        }
    
        console.log(datearray);
    }

Contrary to your expected output I'm saving Date Objects in the array. This has the advantage of giving you more opportunities when working with the Array elements afterwards. This could easily be changed though by changing the line where the Date object is pushed to the array.

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