Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
How to set date back by n months in Javascript

For example the month is June 2020. I want to be able to go back by 12 months, and retrieve the date as June/July 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);

The problem lies with the second to last line, date.getFullYear() returns the current real year (-12) not last year set back 12 months ago. How can I set the date back 12 months so when I attempt to date.getFullYear() I get one year ago?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem with using a Date as in the OP is that in setting the month, you may set it to a date that doesn't exist, e.g. on 31 July setting the date to June gives 31 June, which rolls over to 1 July. You can check and correct for those types of errors, but it's better to just avoid them.

If you just want to generate a 12 month date range based on whole months, you don't need to get that fancy. Given an end month and year, the start will be the month + 1 and year - 1, unless the start month is December in which case the end must be January of the same year, e.g.

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

The getMonth function could use any language, or for just one language could be replaced with an array of month names.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda