javascript 在选择下拉列表中获取最近3个月的姓名

mgdq6dx1  于 2023-04-04  发布在  Java
关注(0)|答案(7)|浏览(113)

我有一个报告,在用户只允许选择一个选项,从过去3个月,如下所示:

我想写一个javaScript函数来实现这一点。
我尝试的是:

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;

}

然后我通过传递参数调用函数:

document.write(getLastMonths(4));

它打印:

201704,201703,201702,201701

这不是我要求的模式。
有人能帮帮我吗?

kulphzqa

kulphzqa1#

看这里。由于使用了 *for循环 *,它稍微短了一点

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());
zte4gxcn

zte4gxcn2#

你可以这样做。只需继续从当前日期中减去one month

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))
xsuvu9jc

xsuvu9jc3#

试试这个方法。把月份名加到一些array中,然后找到索引

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));
blpfk2vs

blpfk2vs4#

由于内部JS名称不是公共的,您必须手动将数字转换为名称。
下面是一个工作示例。它输出的是你在下拉列表中显示月份的方式。

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));
goucqfw6

goucqfw65#

如何使用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.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

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

yks3o0rb6#

我修改了前面的代码,并给出了一个例子:小提琴:https://jsfiddle.net/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());
cu6pst1q

cu6pst1q7#

下面是一个节点12+,ES2020生成器方法在不到5个路口的代码...

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()])

[“2021年7月”,“2021年6月”,“2021年5月”,“2021年4月”]
资料来源:

相关问题