Search code examples
javascriptreactjsdatetimereact-hooksbabeljs

Get the first day of every week until infinity in JavaScript


I want a program that can generate the date of first date of every week, so that I can insert it into the code below

const dateOfTheFirstDay = null;

//preferred format: "April 9, 2023 00:00:01"

const d = new Date(dateOfTheFirstDay);
  setNewWeekTime(d.getTime());

From the code above, I can then get the milliseconds between 1 January 1970 00:00 and the first date of the week.


Solution

  • Here could be the code to achieve your request in javascript

    const startDate = new Date('January 1, 2023');
    const endDate = new Date('December 31, 2023');
    const days = ['Sunday'];
    const sundayDates = [];
    
    for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
       if (days.includes(date.toLocaleString('en-us', { weekday: 'long' }))) {
            sundayDates.push(new Date(date));
       }
    }
    

    sundayDates array will give you the dates you wish