如何在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中文網其他相關文章!