首页 >web前端 >js教程 >如何在 JavaScript 中获取 ISO-8601 周数?

如何在 JavaScript 中获取 ISO-8601 周数?

Barbara Streisand
Barbara Streisand原创
2024-12-06 08:20:13892浏览

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

如何在 JavaScript 中获取 ISO-8601 周数

确定一年中的 ISO-8601 周数,类似于 PHP 的date('W'),请考虑以下方法:

请参阅以下资源: Merlyn 的网站:

  • [与周一起工作](https://www.merlyn.org/js-date6.htm#YWD)

此 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn