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:
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]);
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!