在 JavaScript 中确定周数 就像 PHP 的 date('W')
PHP 的 date('W') 函数计算周数基于 ISO-8601 标准的年份。 ISO-8601 周数从星期一开始,一直持续到星期日。本文演示了如何在 JavaScript 中实现类似的功能。
解决方案
Merlyn 的网站提供了在 JavaScript 中使用几周的全面指南:
根据本指南,以下代码片段返回 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中文网其他相关文章!