Open In App

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:

Example: In this example, we are calculating the total number of weeks till now.






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

Article Tags :