我正在尝试从当前日期算起最近六个月的日期。
~
但是我得到var d = new Date();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
alert(months[d.getMonth()-6]);
答案 0 :(得分:3)
我总是建议使用日期库来协助这些类型的计算。大量支持和示例中最受欢迎的一种是moment.js(https://momentjs.com/)
要使用当前时刻从当前日期开始六个月前是
moment().subtract(6, 'months')
,然后打印月份名称为:
moment().subtract(6, 'months').format('MMMM')
答案 1 :(得分:2)
var d = new Date();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var monthName = months[new Date(d.setMonth(d.getMonth() - 6)).getMonth()];
console.log(monthName)
答案 2 :(得分:1)
您必须像下面那样编写代码-
var d = new Date();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
d.setMonth(d.getMonth() - 6);
console.log(months[d.getMonth()]);
我们需要从日期对象中获取Month,然后将其设置为back(用-6),然后再获取。