简体   繁体   English

获取从提供的 ISO 日期到当前月份和年份的所有月份和年份

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

Suppose I have ISO Date inside an object as:假设我在 object 中有 ISO 日期:

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 :预期的 O/P ->assunming 当前日期是2021 年1 月:

['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.请注意,由于 JavaScript 保存引用,因此您必须先创建一个新的 Date 实例,然后再将其保存到数组中。

    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.与您预期的 output 相反,我将日期对象保存在数组中。 This has the advantage of giving you more opportunities when working with the Array elements afterwards.这样做的好处是在之后使用 Array 元素时为您提供了更多机会。 This could easily be changed though by changing the line where the Date object is pushed to the array.这可以通过更改将日期 object 推送到数组的行来轻松更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM