Sunday, September 22, 2024
Google search engine
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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments