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

207
Vistas
Calculate date from week number, with the week starting on Monday

I need to get the first day of the week by using the week number (weeks starting on Monday). I found this piece of code here: https://stackoverflow.com/a/46343917/13498210. However, the code doesn't seem to work. For example, inputing week 34 returns the date 08-22 (the sunday of the previous week) instead of the correct 08-23.

My question is, is it safe to just "add" one day to the result? Or will that create bugs?

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 Respuestas
Responde la pregunta

0

The code works but has some issues.

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

returns a time value (the return from setDate). To return a Date, it should be two separate statements:

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

Also, looping to find the first Monday is inefficient. It can be calculated from the initial value of firstMonday. Checking for week 53 can also be simplified and the input week number should be tested to ensure it's from 1 to 53.

Lastly, the first couple of days of January may be in the last week of the previous year, so in week 53 getting week 53 with the default year may return the start of week 53 of the wrong year (or undefined, see below). It would be better if the function took two arguments: weekNo and year, where year defaults to the current year and weekNo to the current week.

/* 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 (e.g. 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}`);
});

Where an invalid week number is supplied you have a choice of throwing an error, returning undefined or returning an invalid Date:

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

0

How does this look ?

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
  
  • Working Fiddle
  • More here https://www.py4u.net/discuss/276996
about 4 years ago · Juan Pablo Isaza Denunciar

0

Instead of trying to set the day, month, year, ect.

You could :

  • Create a new Date that is the start of the year.
  • Append the number of milliseconds to get to the weekNo.
  • Remove milleseconds to get to Monday from Friday.
  • Then convert back to a Date object.

Demo:

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 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