Returns the zero-indexed week of the year that a date corresponds to.
Date
constructor and Date.prototype.getFullYear()
to get the first day of the year as a Date
object.Date.prototype.setDate()
, Date.prototype.getDate()
and Date.prototype.getDay()
along with the modulo (%
) operator to get the first Monday of the year.date
and divide with the number of milliseconds in a week.Math.round()
to get the zero-indexed week of the year corresponding to the given date
.-0
is returned if the given date
is before the first Monday of the year.const weekOfYear = date => {
const startOfYear = new Date(date.getFullYear(), 0, 1);
startOfYear.setDate(startOfYear.getDate() + (startOfYear.getDay() % 7));
return Math.round((date - startOfYear) / (7 * 24 * 3600 * 1000));
};
weekOfYear(new Date('2021-06-18')); // 23
JavaScript, Date
Counts the weekdays between two dates.
JavaScript, Date
Calculates the date after adding the given number of business days.
JavaScript, Date
Gets the day of the year (number in the range 1-366) from a Date
object.