skip to Main Content

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.

3

Answers


  1. 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

    Login or Signup to reply.
  2. Since any given day of the week is guaranteed to be 7 days apart you really just need to find an initial reference date and then increment by multiples of 7 either forward or backward. Keep in mind that you will need to decide how to handle timezone issues.

    Here is a generator based solution that will yield any given day forwards from 1583 (to avoid wierdness of dates before adoption of the Gregorian calendar, see proleptic Gregorian calendar).

    function* dayGenerator(day) {
      const addDays = (date, days) => date.setUTCDate(date.getUTCDate() + days);
    
      const ref = new Date(Date.UTC(1583, 0, 1, 12, 0, 0));
      while (ref.toLocaleString('en-us', { weekday: 'long' }) !== day) {
        addDays(ref, 1);
      }
    
      yield new Date(ref);
    
      while (true) {
        yield new Date(addDays(ref, 7));
      }
    }
    
    
    /* Example output */
    
    // The first 10,000 Sundays from Jan 1, 1583
    console.log('Sundays:');
    const sundayGenerator = dayGenerator('Sunday');
    for (let i = 0; i < 10000; i++) {
      const next = sundayGenerator.next().value;
      if (i <= 3 || i === 9999) {
        console.log(
          `Sunday ${i + 1}:`,
          next,
          next.toLocaleString('en-us', { weekday: 'long' })
        );
      }
    }
    
    // A few Tuesdays
    console.log('Tuesdays:');
    const tuesdayGenerator = dayGenerator('Tuesday');
    for (let i = 0; i < 3; i++) {
      const next = tuesdayGenerator.next().value;
      console.log(next, next.toLocaleString('en-us', { weekday: 'long' }));
    }
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    .as-console-row::after { display: none !important; }

    You can make it generic by accepting a startDate and endDate and could further customize to increment backwards if start > end. Here using an alternative arithmetic based method for determining the first matching day after the passed start date.

    function* dayGenerator(
      day,
      startDateISO = '1583-01-01T12:00:00.000Z',
      endDateISO = '9999-12-31T12:00:00.000Z'
    ) {
      const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',];
    
      const ref = new Date(startDateISO);
      ref.setDate(ref.getDate() + ((7 + days.indexOf(day) - ref.getDay()) % 7));
    
      yield new Date(ref);
    
      const endDate = new Date(endDateISO);
      while (ref < endDate) {
        yield new Date(ref.setDate(ref.getDate() + 7));
      }
    }
    
    // Spread the full output of the iterator into an array
    const sundays2023 = [
      ...dayGenerator('Sunday', '2023-01-01T12:00:00Z', '2023-12-31T12:00:00Z'),
    ];
    
    console.log(
      'First: ',
      sundays2023[0],
      sundays2023[0].toLocaleString('en-us', { weekday: 'long' })
    );
    console.log(
      'Last: ',
      sundays2023.at(-1),
      sundays2023.at(-1).toLocaleString('en-us', { weekday: 'long' })
    );

    (curiously 2023 starts and ends on a Sunday)

    Login or Signup to reply.
  3. An efficient algorithm to get an array of Sundays between two dates is to get the Sunday on or before a reference date, then sequentially add 7 days until the end date is reached.

    The following gets all Sundays for the year of the supplied date, with the current date (and hence year) as the default.

    E.g.

    // Return an array of all Sundays in year of
    // supplied date
    function getSundaysInYear(date = new Date()){
      // Get first Sunday of year
      let year = date.getFullYear();
      let start = new Date(year, 0, 7);
      start.setDate(start.getDate() - start.getDay());
      // Set last date of year
      let end = new Date(year, 11, 31);
      // Array of Sundays
      let sundays = [];
    
      while (start <= end) {
        sundays.push(new Date(start));
        start.setDate(start.getDate() + 7);
      }
      return sundays
    }
    
    // Example
    let d = new Date()
    let sundays = getSundaysInYear(d);
    console.log(`${d.getFullYear()} has ${sundays.length} Sundays.` +
      `nFirst: ${sundays[0].toString().substr(0,10)} ` +
      `nLast : ${sundays[sundays.length - 1].toString().substr(0,10)}`
    );
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search