Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

305
Views
JavaScript obtiene el último día del mes, según el año, el mes y el día

Necesito una función JS para obtener la última fecha del mes. como ejemplo, necesito obtener el último miércoles de este mes.

Pasaré Año, Mes y día como argumentos.

 getLastDayOfMonth('2022', '02', 'Wednesday'); function getLastDayOfMonth(year, month, day){ // Output should be like this 2022-02-23 (this is last Wednesday of the month, according to the arguments- Year, month and Day) }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Cree una instancia de Date con el último día del mes y luego retroceda un día a la vez hasta que coincida con el día de la semana que busca.

 const normaliseDay = day => day.trim().toLowerCase() const dayIndex = new Map([ ["sunday", 0], ["monday", 1], ["tuesday", 2], ["wednesday", 3], ["thursday", 4], ["friday", 5], ["saturday", 6], ]) const getLastDayOfMonth = (year, month, dow) => { const day = dayIndex.get(normaliseDay(dow)) // init as last day of month const date = new Date(Date.UTC(parseFloat(year), parseFloat(month), 0)) // work back one-day-at-a-time until we find the day of the week while (date.getDay() != day) { date.setDate(date.getDate() - 1) } return date } console.log(getLastDayOfMonth("2022", "02", "Wednesday"))

Los valores numéricos se analizan como números para que no tengamos problemas con los números octales con ceros.

about 4 years ago · Juan Pablo Isaza Report

0

Puede obtener el último día del mes y luego restar la cantidad requerida de días en función de la diferencia entre el día del final del mes y el día requerido, por ejemplo

 /* Return last instance of week day for given year and month * @param {number|string} year: 4 digit year * @param {number|string} month: calendar month number (1=Jan) * @param {string} day: English week day name, eg Sunday, * Sun, su, case insensitive * @returns {Date} date for last instance of day for given * year and month */ function getLastDayOfMonth(year, month, day) { // Convert day name to index let i = ['su','mo','tu','we','th','fr','sa'].indexOf(day.toLowerCase().slice(0,2)); // Get end of month and eom day index let eom = new Date(year, month, 0); let eomDay = eom.getDay(); // Subtract required number of days eom.setDate(eom.getDate() - eomDay + i - (i > eomDay? 7 : 0)); return eom; } // Examples - last weekdays for Feb 2022 ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'].forEach(day => console.log(day.slice(0,3) + ': ' + getLastDayOfMonth('2022', '02', day).toLocaleDateString('en-GB',{ year:'numeric', month:'short', day:'numeric', weekday:'short' }) ));

En lo anterior:

 new Date(year, month, 0)

aprovecha el hecho de que el mes es un mes calendario, mientras que los meses del constructor de fechas están indexados a 0, por lo que lo anterior establece la fecha en el día cero de marzo, que se resuelve en el último día de febrero.

La parte:

 eom.getDate() - eomDay + i - (i > eomDay? 7 : 0)

resta el índice eomDay para llegar al domingo anterior, luego sumo días para obtener el día requerido. Sin embargo, si va más allá del final del mes (es decir, i es mayor que eomDay , por lo que suma más días que eomDay resta), resta 7 días.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!