Home > Web Front-end > JS Tutorial > How to Get the ISO-8601 Week Number in JavaScript?

How to Get the ISO-8601 Week Number in JavaScript?

Barbara Streisand
Release: 2024-12-06 08:20:13
Original
890 people have browsed it

How to Get the ISO-8601 Week Number in JavaScript?

How to Obtain the ISO-8601 Week Number in JavaScript

To determine the ISO-8601 week number of the year, analogous to PHP's date('W'), consider the following approach:

Refer to the resources at Merlyn's website:

  • [Working with Weeks](https://www.merlyn.org/js-date6.htm#YWD)

This JavaScript code demonstrates the concept:

/*
 * Calculates the ISO week number for a given date.
 *
 * Algorithm adopted from:
 * https://www.merlyn.org/weekcalc.htm#WNR
 *
 * Input:
 *   d: Date object representing the date to calculate the week number for.
 *
 * Output:
 *   Array containing the year and week number.
 */
function getWeekNumber(d) {
    // Clone the date to avoid modifying the original.
    d = new Date(d.getTime());

    // Set the date to the nearest Thursday by adding 4 days and subtracting the day of the week.
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));

    // Determine the first day of the year.
    const yearStart = new Date(d.getFullYear(), 0, 1);

    // Calculate the number of full weeks between the current date and the first day of the year.
    const weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);

    // Return the year and week number in an array.
    return [d.getFullYear(), weekNo];
}

// Example:
const result = getWeekNumber(new Date());
console.log(`Current week: ${result[1]} of year ${result[0]}`);
Copy after login

Using this code, you can obtain the current ISO-8601 week number of the year, which accounts for weeks starting on Mondays, similar to the functionality provided by PHP's date('W').

The above is the detailed content of How to Get the ISO-8601 Week Number in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template