skip to Main Content

this is the array-

months = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];

now, I want to store 3 months’ names in an array- like p = ["march", "feb", "jan"] but this code is giving p = ["march", "march", "feb"] this fails during last 3-4 days of the month. are default days considered to be 28? Please suggest how to improve

        var value = 3;
        var d = new Date();
        var p = [];
        for (let i = 0; i < value; i++) {
          var monthName = this.state.monthsarray[d.getMonth()];
          p.push(monthName);
          d.setMonth(d.getMonth() - 1);
        }
    

2

Answers


  1. Chosen as BEST ANSWER

    I'm still trying to figure out why this duplicates month names but a workaround I'm currently using is-

    for (let i = 0; i < value; i++) {
          var monthName = this.state.monthsarray[d.getMonth()];
          debugger;
          p.push(monthName);
          var y = d.getMonth() - 1;
          d.setMonth(d.getMonth() - 1);
          if(monthName == this.state.monthsarray[d.getMonth()]){
            d.setMonth(d.getMonth() - 1);
          }
        }
    
    

  2. You may consider adjusting your code to handle the edge case where the current month is January by taking the remainder of the previous month index and adding 12.

    Updated Code:

    var value = 3;
    var d = new Date();
    var p = [];
    for (let i = 0; i < value; i++) {
      var prevMonthIndex = (d.getMonth() - 1 + 12) % 12;
      var monthName = this.state.monthsarray[prevMonthIndex].toLowerCase();
      p.push(monthName);
      d.setMonth(d.getMonth() - 1);
    }
    

    Edit: Suggestion based on the comment

    You can even consider creating a new date object in each iteration and use that to get the previous month’s name.

    var value = 3;
    var d = new Date();
    var p = [];
    for (let i = 0; i < value; i++) {
      var prevMonthDate = new Date(d.getFullYear(), d.getMonth() - 1, 1);
      var prevMonthName = this.state.monthsarray[prevMonthDate.getMonth()].toLowerCase();
      p.push(prevMonthName);
      d = prevMonthDate;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search