在 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中文网其他相关文章!