Determine the week number based on a specified starting day for the week

If I have a custom week start day other than Monday, how should the getWeekNumber() prototype for the Date class be modified?

Here is the existing code for calculating the ISO Week Number:

Date.prototype.getWeekNumber = function() {
    // Create a duplicate of this date object
    var target = new Date(this.valueOf());

    // Adjust the day number to suit custom week start day
    var dayNr = (this.getDay() + 6) % 7;

    // According to ISO standards, week 1 begins with the first Thursday of the year.
    // Set the target date to the Thursday within the designated week
    target.setDate(target.getDate() - dayNr + 3);

    // Save millisecond value of the target date
    var firstThursday = target.valueOf();

    // Move target to the first Thursday of the year
    target.setMonth(0, 1);
    
    // If not already a Thursday, adjust to the next Thursday
    if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
    }

    // The week number represents the weeks between the first Thursday of the year and the one in the target week
    return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
};

Answer №1

Enhance your current function by including an additional parameter called weekstart, which allows you to define the starting day of the week. The default value is set to Monday, with 0 representing Sunday and 1 representing Monday.

Date.prototype.getWeekNumber = function(weekstart) {
    var target = new Date(this.valueOf());

    // Set the default value for weekstart and ensure it falls within a valid range        
    if (weekstart === undefined) weekstart = 1;
    weekstart %= 7;

    // Updated offset from (6) to (7 - weekstart)
    var dayNr = (this.getDay() + 7 - weekstart) % 7;
    target.setDate(target.getDate() - dayNr + 3);

    var firstThursday = target.valueOf();

    target.setMonth(0, 1);
    if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
    }

    return 1 + Math.ceil((firstThursday - target) / 604800000);
};    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on utilizing multiple dynamically generated toggle switches efficiently

As a Frontend beginner, I am working on implementing toggle switches using HTML, CSS, and Vanilla JavaScript. Approach: I am generating an HTML table with multiple rows based on the data from my Django database. Each row contains details like name, id, a ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Troubleshooting a dysfunctional Vue.js component

I am currently facing a challenge in getting components to function properly. Interestingly, without the component, everything seems to be working fine (as per the commented code). Here is my HTML snippet: <strong>Total Price:</strong> <sp ...

Building basic objects in TypeScript

My current project involves utilizing an interface for vehicles. export interface Vehicle { IdNumber: number; isNew: boolean; contact: { firstName: string; lastName: string; cellPhoneNumber: number; ...

Encountered an error while trying to retrieve data using the combination of axios, nodejs

Having trouble with my fetch request taking too long and then failing I've tested it on Chrome, Edge, and Postman without success All other fetch requests from the Pixabay API are working perfectly fine I compared my code to previous projects I&apo ...

When attempting to use Arabic characters in my PDF file with LIP, I encounter an error: "TypeError: font must be of type PDFFont or n, but was actually of type NaN"

all I am facing an issue with Arabic characters when trying to use different fonts in my project. I have attempted to encode the Arabic letters using various npm packages, but I keep receiving a TypeError: font must be of type PDFFont or n but was actuall ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

"Partially loaded" when document is ready

Is there a way for me to trigger a function once the element identified by #container has finished loading in the DOM? Instead of waiting for the entire DOM to load using document.ready(), I'd like to start populating #container right after it's ...

Express POST request body is required

I am starting to learn nodejs and express, and while reviewing some code I found this interesting snippet. Can someone please explain what it means and how I can send a POST request to it using cURL? There are no specified data fields. app.post('/&apo ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Enhancing Navbar Design with Tailwind CSS in NextJS and React

I have not worked with React in a while and just started learning Next.Js. I am trying to figure out how to change the background of my Navbar using Tailwind CSS based on a boolean value "current" (true/false) depending on which page the user is on with Ne ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Utilize the split functionality only when the character you want to split by is found in

Consider the following situation: I have 6 string variables that contain special characters. I stored these 6 strings in an array like this: arr=[str1,str2,str3...); arr=escape(arr); due to the presence of special characters in some string variables. ...

Issue with toggling JS checkboxes selection

Seeking assistance in expanding my knowledge of Javascript. I have a form with checkboxes and a JavaScript function that allows toggling between selecting and deselecting all the boxes. Everything is functioning as intended so far. The challenge arises f ...

What is the best way to implement client-side shopping cart calculations using jQuery?

https://i.stack.imgur.com/aOajr.png Here is the content of my shopping cart. Below, I will explain the flow. [product image clicked] -> ajax request fetches details from database for that particular product id and appends (product name,id and price ...

React Checkbox Sum Component - Effortlessly Improve User Experience

Looking for assistance with passing checkbox values to a React component in my app. I'm currently implementing a food list display using JSON data, but I'm unsure how to transfer the checkbox values to another component. For reference, here&apos ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

What is the process for utilizing the TypeScript compiler with nodejs?

I have a sample code saved in a file called hello.ts Upon the completion of nodejs setup on Windows, execute the following command to install typescript: npm install -g typescript Is there a way to compile hello.ts directly with node.js? While using "T ...

Experiencing the Pause: A Fresh Take on

I'm currently using this slideshow for a project, and I need to understand if it's possible to resume its interval. The current issue is that when you hover over the slideshow, the progress bar stops. But once you remove the mouse, it continues f ...