Home > Web Front-end > JS Tutorial > How to Calculate ISO Week Numbers in JavaScript, Just Like PHP's `date('W')`?

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

DDD
Release: 2024-12-12 22:48:16
Original
682 people have browsed it

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

Determining Week Number in JavaScript Like PHP's date('W')

PHP's date('W') function calculates the week number of the year based on ISO-8601 standards. The ISO-8601 week number begins on Monday and runs through Sunday. This article demonstrates how to achieve similar functionality in JavaScript.

Solution

Merlyn's website provides a comprehensive guide to working with weeks in JavaScript:

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

Based on this guide, the following code snippet returns the ISO-8601 week number of a given date:

/* 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]);
Copy after login

This code relies on UTC methods to avoid issues during daylight saving and specific year-start scenarios. The output displays both the current year and week number, similar to PHP's date('W') function.

The above is the detailed content of How to Calculate ISO Week Numbers in JavaScript, Just Like PHP's `date('W')`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template