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:
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]}`);
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!