最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get last 3 months names in select dropdown - Stack Overflow

programmeradmin3浏览0评论

I have a report where in the user is only allowed to select an option from last 3 months as shown below :

I want to write a javaScript function to achieve this.

What I tried was :

function getLastMonths(n) {

    var months = new Array();

    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;

    var i = 0;
    do {
        months.push(year + (month > 9 ? "" : "0") + month);
        if(month == 1) {
            month = 12;
            year--;
        } else {
            month--;
        }
        i++;
    } while(i < n);

    return months;

}

Then I called the function by passing parameters :

document.write(getLastMonths(4));

It prints :

201704,201703,201702,201701

Which is not the pattern I require it in.

Can anyone help me out here ?

I have a report where in the user is only allowed to select an option from last 3 months as shown below :

I want to write a javaScript function to achieve this.

What I tried was :

function getLastMonths(n) {

    var months = new Array();

    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;

    var i = 0;
    do {
        months.push(year + (month > 9 ? "" : "0") + month);
        if(month == 1) {
            month = 12;
            year--;
        } else {
            month--;
        }
        i++;
    } while(i < n);

    return months;

}

Then I called the function by passing parameters :

document.write(getLastMonths(4));

It prints :

201704,201703,201702,201701

Which is not the pattern I require it in.

Can anyone help me out here ?

Share Improve this question asked Apr 27, 2017 at 8:22 Ashish BahlAshish Bahl 1,4921 gold badge18 silver badges28 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 4

Take a look here. It's a bit shorter thanks to for loop

function getLast3Months() {

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

  var today = new Date();
  var last3Months = []

  for (i = 0; i < 3; i++) {
    last3Months.push(monthNames[(today.getMonth() - i)] + ' - ' +today.getFullYear()  );
  }
  return last3Months;
}

document.write(getLast3Months());

You can do it like this. Simply go on subtracting one month from current date

function getLastMonths(n) {
  var m =['January','February','March','April','May','June','July','August','September','October','November','December'];
  var last_n_months =[]
  var d = new Date()
  for(var i=0;i<n;i++){
    last_n_months[i] = m[d.getMonth()]+ ' - ' + d.getFullYear().toString()
    d.setMonth(d.getMonth()-1)
  }
  return last_n_months
}
console.log(getLastMonths(3))

Try this . add month name into some array then find the index

function getLastMonths(n) {
var m =['','Jan','Feb','Mar','Aprl','May','Jun','July','Aug','Sep','Oct','Nov','Dec'];
  var months = new Array();

  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth()+1;

  var i = 0;
  do {
    months.push( m[parseInt((month > 9 ? "" : "0") + month)]+'-'+year);
    if (month == 1) {
      month = 12;
      year--;
    } else {
      month--;
    }
    i++;
  } while (i < n);

  return months;

}
document.write(getLastMonths(4));

You have to convert the number to the name manually due to internal JS names not being public.

See below for working example. This outputs exactly how you shown the months in the dropdown.

var monthNames = ["January", "February", "March", "April", "May", "June",
      "July", "August", "September", "October", "November", "December"
];
function getLastMonths(n) {

    var months = new Array();

    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1;

    var i = 0;
    do {
        months.push(monthNames[month] + ' - ' + year);
        if(month == 1) {
            month = 12;
            year--;
        } else {
            month--;
        }
        i++;
    } while(i < n);

    return months;

}

document.write(getLastMonths(4));

How about using moment.js?

var getLastMonths = function(n) {
  var arr = new Array();

  arr.push(moment().format('YYYY MM'));

  for(var i=1; i< 3; i++){
    arr.push(moment().add(i*-1, 'Month').format('YYYY MM'));
  }
  
  return arr;
}

var appendOptions = function(arr) {
  var html = '';
  
  for(var i=0; i<arr.length; i++) {
    html += '<option value="' + arr[i] + '">' + arr[i] + '</option>'  
  }

  document.getElementById('select-months').innerHTML = html;

}

var months = getLastMonths(4);
appendOptions(months);
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>

<select id="select-months"></select>

I have modified the earlier code and given one example: fiddle: https://jsfiddle/asutosh/rogpxwah/

function getLast3Months() {

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

  var today = new Date(2019,3,12);
  var month=today.getMonth();
  var last3Months = []

  for (i = 0; i < 3; i++) {
      var newMonth=(today.getMonth() - i);
      var newYear=today.getFullYear();

      monthInWords=monthNames[newMonth];
      if(newMonth<0){

       newYear=today.getFullYear() - 1;
       monthInWords=monthNames[12+newMonth];
      }
     var newDate= new Date(today.getDate(), newMonth, newYear);
     last3Months.push(monthInWords + ' - ' +newYear  );
  }
  return last3Months;
}

window.document.write(getLast3Months());

The following is a Node 12+, ES2020 Generator method in less than ~5 junctions of code...

function* lastMonths(start = 0, end = 4, step = 1, D = new Date()) {
  const o = new Intl.DateTimeFormat("en-US" , { month: "long", year: "numeric" })
  for (let i = start; i < end; i += step) {
    const past = new Date(D)
    void past.setMonth(D.getMonth() - i)
    const localeStr = o.format(past).replace(' ', ' - ')
    yield localeStr
  }
  return D
}
console.log([...lastMonths()])

[ "July - 2021", "June - 2021", "May - 2021", "April - 2021" ]

Sources:

  • https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
  • https://developer.mozilla/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
发布评论

评论列表(0)

  1. 暂无评论