Search code examples
javascriptdatedate-fns

When you know what week it is, how to find out the start date of the week


Through the 'date-fns' module, I am receiving numbers of how many weeks the date is this year.

const current = '2022-03-10'
const weekNumber = getWeek(current, 1) // 11

On the contrary, if you only know the numbers, you want to know how to do the first date of the week number.

The way I want to know.

const weekNumber = 11;
const weekOfstartDate = anyFunc(weekNumber) // '2022-03-07'

Do you know the answer to this solution?


Solution

  • You can use the I token:

    var dateFns = require("date-fns");
    console.log(dateFns.parse('10','I', new Date()));
    

    At npm.runkit.com that returns a date for Mon 7 Mar 2022. It seems date-fns assumes the year of the current week. I have no idea how to specify the year, attempting:

    console.log(dateFns.parse('2022-10','YYYY-II', new Date(),{
      useAdditionalWeekYearTokens: true
    }));
    

    Throws a range error: The format string mustn't contain YYYY and II at the same time. Similarly for "2022W10" and tokens "YYYY'W'II", it says Y and I tokens can't be in the same format string.

    A function to do the same thing is:

    // Returns the first day (Monday) of the specified week
    // Year defaults to the current local calendar year
    function getISOWeek(w, y = new Date().getFullYear()) {
      let d = new Date(y, 0, 4);
      d.setDate(d.getDate() - (d.getDay() || 7) + 1 + 7*(w - 1));
      return d;
    }
    
    // Mon Mar 14 2022
    console.log(getISOWeek(11).toString());
    // Mon Jan 02 2023
    console.log(getISOWeek(1,2023).toString());
    // Mon Dec 28 2026
    console.log(getISOWeek(53,2026).toString());

    A robust function should validate the input such that the week number is 1 to 53 and that 53 is only permitted for years that have 53 weeks.