Calculate current week number in JavaScript
Calculating the current week number involves determining which week of the year the current date falls into. This is often based on a system where weeks start on a specific day, typically Sunday or Monday.
Example:
The week number of january 1 = either week 52 or week 1
Explanation: From the below calendar we can see that Jan 1 is in last week52 of the previous year. If it was Monday, then Jan1 would be week 1
Approach:
- Date Initialization: Ensure currentDate is set to either the provided date object or the current date using new Date().
- Calculate January 1st: Initialize januaryFirst to the beginning of the current year using new Date(currentDate.getFullYear(), 0, 1).
- Days to Next Monday: Determine the number of days to the next Monday from January 1st using conditional logic.
- Calculate Next Monday: Set nextMonday to the date of the next Monday following January 1st.
- Return Week Number: Compare currentDate with nextMonday and calculate the week number accordingly, returning the result.
Example: In this example, we are calculating the total number of weeks till now.
Javascript
function getDateWeek(date) { const currentDate = ( typeof date === 'object' ) ? date : new Date(); const januaryFirst = new Date(currentDate.getFullYear(), 0, 1); const daysToNextMonday = (januaryFirst.getDay() === 1) ? 0 : (7 - januaryFirst.getDay()) % 7; const nextMonday = new Date(currentDate.getFullYear(), 0, januaryFirst.getDate() + daysToNextMonday); return (currentDate < nextMonday) ? 52 : (currentDate > nextMonday ? Math.ceil( (currentDate - nextMonday) / (24 * 3600 * 1000) / 7) : 1); } const currentDate = new Date(); const weekNumber = getDateWeek(); console.log( "Week number of " + currentDate + " is : " + weekNumber); |
Output
Week number of Mon Mar 11 2024 04:57:07 GMT+0000 (Coordinated Universal Time) is : 11
the