如何在Javascript中将日期向后设置n个月



例如,月份为2020年6月。我希望能够在12个月前返回,并将日期检索为2019年6月/7月。

let month_val = 6;
let year_val = 2020;
let n_val = 12;
let month_names = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
let date = new Date();
let end_month_text = month_names[month_val - 1];
end_month_text += " " + year_val;
date.setMonth(month_val); //set to month in URL
date.setMonth(date.getMonth() - n_val); //setting back by n_val months
let start_month_text = month_names[date.getMonth()];
start_month_text += " " + date.getFullYear();
console.log(start_month_text + " - " + end_month_text);

问题在于倒数第二行,date.getFullYear()返回当前实际年份(-12(,而不是12个月前的最后一年。我如何将日期设置为12个月,这样当我尝试date.getFullYear()时,我一年前就得到了?

在OP中使用日期的问题是,在设置月份时,您可能会将其设置为不存在的日期,例如,在7月31日,将日期设置为6月31日即为6月1日,该日期将滚动到7月1日。您可以检查并更正这些类型的错误,但最好只是避免它们。

如果你只想根据整个月生成一个12个月的日期范围,你不需要那么花哨。给定一个结束的月份和年份,开始的月份将是+1和-1,除非开始的月份是12月,在这种情况下,结束必须是同一年的1月,例如

// month is calendar month number, 1 == Jan
function getMonthName(month = new Date().getMonth() + 1) {
// Use a Date to get the month name
return new Date(2000, month - 1).toLocaleString('en',{month:'long'});
}
// month is end calendar month number
// year is end year
function getDateRange(month, year) {
// If month is 12, don't subtract 1 from year
return `${getMonthName(month+1)} ${year - (month == 12? 0 : 1)} - ` +
`${getMonthName(month)} ${year}`; 
}
// Range ending June 2021
console.log(getDateRange(6, 2021)); // July 2020 - June 2021
// Range ending December 2021
console.log(getDateRange(12, 2021)); // January 2021 - December 2021
// Range ending January 2021
console.log(getDateRange(1, 2021)); // February 2020 - January 2021
// Range ending in current month and year
let d = new Date();
console.log(getDateRange(d.getMonth() + 1, d.getFullYear()));

getMonth函数可以使用任何语言,或者对于一种语言,可以用月份名称数组替换。

最新更新