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

213
Views
Calcule la fecha a partir del número de semana, con la semana que comienza el lunes

Necesito obtener el primer día de la semana usando el número de semana (semanas que comienzan el lunes). Encontré este fragmento de código aquí: https://stackoverflow.com/a/46343917/13498210 . Sin embargo, el código no parece funcionar. Por ejemplo, ingresar la semana 34 devuelve la fecha 08-22 (el domingo de la semana anterior) en lugar del 08-23 correcto.

Mi pregunta es, ¿es seguro simplemente "agregar" un día al resultado? ¿O eso creará errores?

 function getFirstMondayOfWeek(weekNo) { var firstMonday = new Date(new Date().getFullYear(), 0, 4, 0, 0, 0, 0); while (firstMonday.getDay() != 1) { firstMonday.setDate(firstMonday.getDate() - 1); } if (1 <= weekNo && weekNo <= 52) return firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1)); firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1)); if (weekNo = 53 && firstMonday.getDate() >= 22 && firstMonday.getDate() <= 28) return firstMonday; //JUST ADD A DAY HERE return null; }
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El código funciona pero tiene algunos problemas.

 return firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));

devuelve un valor de tiempo (el retorno de setDate ). Para devolver una Fecha, deben ser dos declaraciones separadas:

 firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1)); return firstMonday;

Además, hacer un bucle para encontrar el primer lunes es ineficiente. Se puede calcular a partir del valor inicial de firstMonday . La verificación de la semana 53 también se puede simplificar y el número de semana de entrada debe probarse para asegurarse de que sea del 1 al 53.

Por último, los primeros días de enero pueden estar en la última semana del año anterior, por lo que en la semana 53 obtener la semana 53 con el año predeterminado puede devolver el inicio de la semana 53 del año incorrecto (o indefinido, ver más abajo). Sería mejor si la función tomara dos argumentos: número de semana y año, donde el año por defecto es el año actual y el número de semana es la semana actual.

 /* Return date for Monday of supplied ISO week number * @param {number|string} weekNo - integer from 1 to 53 * @returns {Date} Monday of chosen week or * undefined if input is invalid */ function getFirstMondayOfWeek(weekNo) { let year = new Date().getFullYear(); // Test weekNo is an integer in range 1 to 53 if (Number.isInteger(+weekNo) && weekNo > 0 && weekNo < 54) { // Get to Monday of first ISO week of year var firstMonday = new Date(year, 0, 4); firstMonday.setDate(firstMonday.getDate() + (1 - firstMonday.getDay())); // Add required weeks firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1)); // Check still in correct year (eg weekNo 53 in year of 52 weeks) if (firstMonday.getFullYear() <= year) { return firstMonday; } } // If not an integer or out of range, return undefined return; } // Test weeks, there is no week 53 in 2021 [0, '1', 34, 52, 53, 54, 'foo'].forEach(weekNo => { let date = getFirstMondayOfWeek(weekNo); console.log(`Week ${weekNo}: ${date? date.toDateString() : date}`); });

Cuando se proporciona un número de semana no válido, tiene la opción de arrojar un error, devolver indefinido o devolver una fecha no válida:

 return new Date(NaN);
about 4 years ago · Juan Pablo Isaza Report

0

Cómo se ve esto ?

HTML

 <div id="datediv"></div>

JS

 var dateDiv=document.getElementById('datediv') function getDateOfWeek(w, y) { let date = new Date(y, 0, (1 + (w - 1) * 7)); // Elle's method date.setDate(date.getDate() + (1 - date.getDay())); // 0 - Sunday, 1 - Monday etc return date } var firstMonday = getDateOfWeek(36,2021) dateDiv.innerText=firstMonday
  • violín de trabajo
  • Más aquí https://www.py4u.net/discuss/276996
about 4 years ago · Juan Pablo Isaza Report

0

En lugar de intentar configurar el day , month , year , etc.

Tú podrías :

  • Cree una nueva Date que sea el comienzo del año.
  • Agregue el número de milisegundos para llegar al número de weekNo .
  • Quitar milésimas de segundo para llegar al Monday del Friday .
  • Luego, vuelva a convertirlo en un objeto Date .

Manifestación:

 function getFirstMondayOfWeek(weekNo) { return new Date(new Date(new Date().getFullYear(), 0).getTime() + weekNo * 604800000 - 345600000); } for (let i = 1; i <= 52; i++) console.log(`Week number ${i}:`, getFirstMondayOfWeek(i).toDateString());

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!