MomentJs monday by week number bug

Viewed 583

I have a function that grabs the date key with format of YYYY-MM-DD, eg. 2021-03-29 (monday) get its week number (13), and using that, get that week number's monday, in case of 2021-03-29 it would be the same day, incase of 2021-03-30 it should be 2021-03-29 etc, as long as it's on the same week (by week number)

I have created a sandbox for it.

http://jsfiddle.net/x6sL8k7e/1/

Test code

const dateKey = "2021-03-29"
const weekNumber = moment(dateKey, 'YYYY-MM-DD').isoWeek() // getting week nr - 13
    
      
const date = moment(dateKey, 'YYYY-MM-DD')
        .clone()
        .week(weekNumber) // want to get monday for week #13
        .day('Monday')
        
console.log('date', date.format('YYYY-MM-DD'))

PS. It works flawlessly with this year's dates (any date)

2 Answers

Ciao, I solved your problem by replacing isoWeek with week like this:

const dateKey = "2021-03-29"
const weekNumber = moment(dateKey, 'YYYY-MM-DD').week()
    console.log(weekNumber)
      
      const date = moment(dateKey, 'YYYY-MM-DD')
        .clone()
        .week(weekNumber)
        .day('Monday')
        
        console.log('date', date.format('YYYY-MM-DD'))

Here your code modified.

Anyway, I understand your problem and could be related to the fact that 2020 has 53 weeks and 2021 has 52 weeks.

enter image description here

So isoWeek retruns correctly the 13th week, but week retruns 14th (maybe) because it consider every year composed by 52 weeks.

Approach I went for was a bit different in the end. Instead of getting the week number, and then getting the monday of that week number, I simply decided to get the date, get its weekday, eg. Tuesday, and based on that find the monday.

  const dayOfTheWeekNumber = toNumber(
    moment(dateKey, 'YYYY-MM-DD')
      .clone()
      .format('e')
  )
  const date = moment(dateKey).subtract(
    dayOfTheWeekNumber === 0 ? 6 : dayOfTheWeekNumber - 1,
    'days'
  )
Related