Por ejemplo, el mes es junio de 2020. Quiero poder retroceder 12 meses y recuperar la fecha como junio/julio de 2019.
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);
El problema radica en la penúltima línea, date.getFullYear()
devuelve el año real actual (-12), no el último año retrocedido hace 12 meses. ¿Cómo puedo configurar la fecha 12 meses atrás para que cuando intente date.getFullYear()
obtenga hace un año?
El problema con el uso de una Fecha como en el OP es que al configurar el mes, puede configurarlo en una fecha que no existe, por ejemplo, el 31 de julio al configurar la fecha en junio da el 31 de junio, que se transfiere al 1 de julio. Puede verificar y corregir esos tipos de errores, pero es mejor evitarlos.
Si solo desea generar un rango de fechas de 12 meses basado en meses completos, no necesita ser tan sofisticado. Dado un mes y un año final, el inicio será el mes + 1 y el año - 1, a menos que el mes inicial sea diciembre, en cuyo caso el final debe ser enero del mismo año, por ejemplo
// 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()));
La función getMonth podría usar cualquier idioma, o para un solo idioma podría reemplazarse con una matriz de nombres de meses.