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
Here could be the code to achieve your request in javascript
sundayDates
array will give you the dates you wishSince 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).
You can make it generic by accepting a
startDate
andendDate
and could further customize to increment backwards ifstart > end
. Here using an alternative arithmetic based method for determining the first matching day after the passed start date.(curiously 2023 starts and ends on a Sunday)
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.