Monday, July 15, 2024
HomeLanguagesJavascriptCalculate current week number in JavaScript

Calculate current week number in JavaScript

The week number indicates the number of weeks that have been completed in the current year.

Example:

The week number of january 1  = week 1
The week number of january 30 = week 5

Explanation: From the below calendar we can see that Jan 1 is in week 1 and Jan 30 in week 5

In the process of calculating the current week’s number, we will the following numbers.

JavaScript getFullYear() Method: The getFullYear() returns the full year (4 digits) of a date.

Syntax:

Date.getFullYear()

JavaScript getDay() Method: The getDay() method returns the day of the week (0 to 6) of a date.

Syntax:

Date.getDay()

Approach: Initialize the current date to a variable using a new Date() which by default returns the current date. Initialize the starting date of the current year ( i.e. Jan 1) to startDate. Calculate the difference between the two dates in days by subtracting startDate from currentDate.

  • This returns the difference between dates in milliseconds.
  • now dividing the result by the total milliseconds in a day gives a difference between dates in days.

Add the number of days to the current weekday using getDay() and divide it by 7. We will get the current week’s number.

Example: Below code will illustrate the above example:

Javascript




currentDate = new Date();
startDate = new Date(currentDate.getFullYear(), 0, 1);
var days = Math.floor((currentDate - startDate) /
    (24 * 60 * 60 * 1000));
 
var weekNumber = Math.ceil(days / 7);
 
// Display the calculated result      
console.log("Week number of " + currentDate +
    " is :   " + weekNumber);


Output:

Week number of Fri Dec 30 2022 13:53:43 GMT+0530 (India Standard Time) is :   52

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments