首頁 > web前端 > js教程 > 如何在 JavaScript 中取得 ISO 週數?

如何在 JavaScript 中取得 ISO 週數?

DDD
發布: 2024-12-30 16:49:08
原創
868 人瀏覽過

How to Get the ISO Week Number in JavaScript?

在JavaScript 中取得週數,就像PHP 的date('W')

PHP 的date('W') 函數傳回目前ISO-8601 週數年,從星期一開始。我們可以使用以下方法在JavaScript 中獲得相同的結果:

使用外部函式庫

以下連結中提供的外部函式庫可用於計算ISO 週給定日期的編號:

自訂 JavaScript 程式碼

或者,我們可以實作自訂 JavaScript函數計算星期數:

/* For a given date, get the ISO week number
 *
 * Based on information at:
 *
 *    THIS PAGE (DOMAIN EVEN) DOESN'T EXIST ANYMORE UNFORTUNATELY
 *    http://www.merlyn.demon.co.uk/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());
document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);
登入後複製

用法

var date = new Date("2018-01-15");
var weekNumber = getWeekNumber(date);
console.log(weekNumber[1]); // Output: 3
登入後複製

以上是如何在 JavaScript 中取得 ISO 週數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板