如何在 JavaScript 中获取 ISO-8601 周数
确定一年中的 ISO-8601 周数,类似于 PHP 的date('W'),请考虑以下方法:
请参阅以下资源: Merlyn 的网站:
此 JavaScript 代码演示了这个概念:
/* * 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]}`);
使用此代码,您可以获取当前 ISO-8601 一年中的周数,即从星期一开始的周数,类似于 PHP 的 date('W') 提供的功能。
以上是如何在 JavaScript 中获取 ISO-8601 周数?的详细内容。更多信息请关注PHP中文网其他相关文章!