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

315
Views
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 answers
Answer question

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