Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

325
Visualizações
How to get weeks between a date and weekofyear, year tuple

How do I get the number of weeks between a given date and (weekofyear, year) tuple? Preferably using momentjs.

function getWeeksBetweenStartDate(weekOfYear, year)
  const date = moment().set({
    year: 1982,
    month: 3,
    day: 18,
    hour: 0,
    minute: 0,
    second: 0,
  });
  const weeksSinceDate =
    moment()
      .year(year)
      .isoWeek(weekOfYear)
      .day(0)
      .hour(0)
      .minute(0)
      .subtract(date)
      .weeks() ;
}

function getWeeks(date) {
  return getWeeksBetweenStartDate(date.isoWeeks(), date.year());
}

  getWeeks(
    moment().set({
      year: 1982,
      month: 3,
      day: 21,
      hour: 0,
    })
  )  // returns 0

  getWeeks(
    moment().set({
      year: 1982,
      month: 3,
      day: 23,
      hour: 0,
      minute: 0,
    })
  ) // returns 1

Even though the two example dates are part of same week, a different week delta is returned.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are several mistakes in the code I think:

  • First, you should not do that .subtract(date) in getWeeksBetweenStartDate, after subtraction, the date will become nearby 1970 (The UTC epoch). Instead, you should
  • You should not use the isoWeeks method, because in isoWeeks, Monday is the beginning of a week.
  • Had Better set moment.locale('us') at the beginning, to ensure a week always begins at Sunday.

The following maybe the correct code you expect:


moment.locale("us")
 
function getWeeksBetweenStartDate(date) {
  const weeksBegin = moment().set({
    year: 1982,
    month: 3,
    day: 18,
    hour: 0,
    minute: 0,
    second: 0,
  }).weeks();
  const weeksEnd = date.weeks();
  return weeksEnd - weeksBegin;
}

function getWeeks(date) {
  return getWeeksBetweenStartDate(date);
}

console.log(getWeeks(
    moment().set({
      year: 1982,
      month: 3,
      day: 21,
      hour: 0,
    })
    )  // returns 0
    ,
    getWeeks(
    moment().set({
      year: 1982,
      month: 3,
      day: 23,
      hour: 0,
      minute: 0,
    })
    ) // returns 1
)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda