首頁 >web前端 >js教程 >如何在 JavaScript 中計算 ISO 週數,就像 PHP 的「date('W')」一樣?

如何在 JavaScript 中計算 ISO 週數,就像 PHP 的「date('W')」一樣?

DDD
DDD原創
2024-12-12 22:48:16759瀏覽

How to Calculate ISO Week Numbers in JavaScript, Just Like PHP's `date('W')`?

在JavaScript 中確定週數就像PHP 的date('W')

PHP 的date('W') 函數計算週數是根據ISO-8601 標準的年份。 ISO-8601 週數從星期一開始,一直持續到星期日。本文示範如何在 JavaScript 中實作類似的功能。

解決方案

Merlyn 的網站提供了在 JavaScript 中使用幾週的全面指南:

  • [與週](https://www.merlyn.org/2005/11/04/working-with-weeks/)

根據本指南,以下程式碼片段返回ISO-8601週給定日期的編號:

/* For a given date, get the ISO week number
 *
 * Based on information at:
 *
 *    https://www.merlyn.org/weekcalc.htm#WNR
 *
 * Algorithm is to find nearest thursday, it's year
 * is the year of the week number. Then get weeks
 * between that date and the first day of that year.
 *
 * Note that dates in one year can be weeks of previous
 * or next year, overlap is up to 3 days.
 *
 * e.g. 2014/12/29 is Monday in week  1 of 2015
 *      2012/1/1   is Sunday in week 52 of 2011
 */
function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
    // Get first day of year
    var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
    // Return array of year and week number
    return [d.getUTCFullYear(), weekNo];
}

var result = getWeekNumber(new Date());
console.log('It\'s currently week ' + result[1] + ' of ' + result[0]);

此程式碼依賴UTC 方法來避免夏令時和特定年初場景期間出現問題。輸出顯示目前年份和週數,類似於 PHP 的 date('W') 函數。

以上是如何在 JavaScript 中計算 ISO 週數,就像 PHP 的「date('W')」一樣?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn