像在 PHP 中一样在 JavaScript 中获取一年中的一周
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6117814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get week of year in JavaScript like in PHP
提问by PeeHaa
How do I get the current weeknumber of the year, like PHP's date('W')
?
我如何获得一年中的当前周数,比如 PHP 的date('W')
?
It should be the ISO-8601week number of year, weeks starting on Monday.
它应该是ISO-8601 年中的周数,从星期一开始。
回答by RobG
You should be able to get what you want here: http://www.merlyn.demon.co.uk/js-date6.htm#YWD.
你应该能够在这里得到你想要的东西:http: //www.merlyn.demon.co.uk/js-date6.htm#YWD。
A better link on the same site is: Working with weeks.
同一站点上更好的链接是:Working with week。
Edit
编辑
Here is some code based on the links provided and that posted eariler by Dommer. It has been lightly tested against results at http://www.merlyn.demon.co.uk/js-date6.htm#YWD. Please test thoroughly, no guarantee provided.
这是一些基于提供的链接和 Dommer 早期发布的代码。它已针对http://www.merlyn.demon.co.uk/js-date6.htm#YWD 上的结果进行了轻微测试。请彻底测试,不提供任何保证。
Edit 2017
编辑 2017
There was an issue with dates during the period that daylight saving was observed and years where 1 Jan was Friday. Fixed by using all UTC methods. The following returns identical results to Moment.js.
在实行夏令时期间的日期和 1 月 1 日是星期五的年份存在问题。通过使用所有 UTC 方法修复。下面将向 Moment.js 返回相同的结果。
/* For a given date, get the ISO week number
*
* Based on information at:
*
* 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]);
Hours are zeroed when creating the "UTC" date.
创建“UTC”日期时,小时数归零。
Minimized, prototype version (returns only week-number):
最小化的原型版本(仅返回周数):
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
document.write('The current ISO week number is ' + new Date().getWeekNumber());
Test section
测试部分
In this section, you can enter any date in YYYY-MM-DD format and check that this code gives the same week number as Moment.js ISO week number (tested over 50 years from 2000 to 2050).
在本节中,您可以输入 YYYY-MM-DD 格式的任何日期,并检查此代码是否提供与 Moment.js ISO 周数相同的周数(从 2000 年到 2050 年测试了 50 多年)。
Date.prototype.getWeekNumber = function(){
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7)
};
function checkWeek() {
var s = document.getElementById('dString').value;
var m = moment(s, 'YYYY-MM-DD');
document.getElementById('momentWeek').value = m.format('W');
document.getElementById('answerWeek').value = m.toDate().getWeekNumber();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Enter date YYYY-MM-DD: <input id="dString" value="2021-02-22">
<button onclick="checkWeek(this)">Check week number</button><br>
Moment: <input id="momentWeek" readonly><br>
Answer: <input id="answerWeek" readonly>
回答by sixdays
回答by nvd
As said above but without a class:
如上所述,但没有类:
let now = new Date();
let onejan = new Date(now.getFullYear(), 0, 1);
week = Math.ceil( (((now - onejan) / 86400000) + onejan.getDay() + 1) / 7 );
回答by orafaelreis
Accordily http://javascript.about.com/library/blweekyear.htm
相应地http://javascript.about.com/library/blweekyear.htm
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var millisecsInDay = 86400000;
return Math.ceil((((this - onejan) /millisecsInDay) + onejan.getDay()+1)/7);
};
回答by Brad Koch
Jacob Wright's Date.format()
library implements date formatting in the style of PHP's date()
function and supports the ISO-8601 week number:
Jacob Wright 的Date.format()
库以 PHPdate()
函数的风格实现了日期格式,并支持 ISO-8601 周数:
new Date().format('W');
It may be a bit overkill for just a week number, but it does support PHP style formatting and is quite handy if you'll be doing a lot of this.
对于仅一周的数字来说,这可能有点矫枉过正,但它确实支持 PHP 样式格式,如果您要进行大量此类操作,它会非常方便。
回答by Dmitry Volokh
getWeekOfYear: function(date) {
var target = new Date(date.valueOf()),
dayNumber = (date.getUTCDay() + 6) % 7,
firstThursday;
target.setUTCDate(target.getUTCDate() - dayNumber + 3);
firstThursday = target.valueOf();
target.setUTCMonth(0, 1);
if (target.getUTCDay() !== 4) {
target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
}
return Math.ceil((firstThursday - target) / (7 * 24 * 3600 * 1000)) + 1;
}
Following code is timezone-independent (UTC dates used) and works according to the https://en.wikipedia.org/wiki/ISO_8601
以下代码与时区无关(使用 UTC 日期)并根据https://en.wikipedia.org/wiki/ISO_8601 工作
回答by Hans Petersen
Get the weeknumber of any given Date
获取任何给定日期的周数
function week(year,month,day) {
function serial(days) { return 86400000*days; }
function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
function weekday(date) { return (new Date(date)).getDay()+1; }
function yearserial(date) { return (new Date(date)).getFullYear(); }
var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day),
date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
}
Example
例子
console.log(
week(2016, 06, 11),//23
week(2015, 9, 26),//39
week(2016, 1, 1),//53
week(2016, 1, 4),//1
week(new Date(2016, 0, 4)),//1
week("11 january 2016")//2
);
回答by Tigran
This adds "getWeek" method to Date.prototype which returns number of week from the beginning of the year. The argument defines which day of the week to consider the first. If no argument passed, first day is assumed Sunday.
这将“getWeek”方法添加到 Date.prototype,它返回从年初开始的周数。该参数定义首先考虑一周中的哪一天。如果没有传递参数,则假定第一天是星期日。
/**
* Get week number in the year.
* @param {Integer} [weekStart=0] First day of the week. 0-based. 0 for Sunday, 6 for Saturday.
* @return {Integer} 0-based number of week.
*/
Date.prototype.getWeek = function(weekStart) {
var januaryFirst = new Date(this.getFullYear(), 0, 1);
if(weekStart !== undefined && (typeof weekStart !== 'number' || weekStart % 1 !== 0 || weekStart < 0 || weekStart > 6)) {
throw new Error('Wrong argument. Must be an integer between 0 and 6.');
}
weekStart = weekStart || 0;
return Math.floor((((this - januaryFirst) / 86400000) + januaryFirst.getDay() - weekStart) / 7);
};
回答by thdoan
The code below calculates the correct ISO 8601 week number. It matches PHP's date("W")
for every week between 1/1/1970 and 1/1/2100.
下面的代码计算正确的 ISO 8601 周数。它date("W")
在 1/1/1970 和 1/1/2100 之间每周匹配 PHP 。
/**
* Get the ISO week date week number
*/
Date.prototype.getWeek = function () {
// Create a copy of this date object
var target = new Date(this.valueOf());
// ISO week date weeks start on Monday, so correct the day number
var dayNr = (this.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week with the first Thursday of that year
// Set the target date to the Thursday in the target week
target.setDate(target.getDate() - dayNr + 3);
// Store the millisecond value of the target date
var firstThursday = target.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
target.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((firstThursday - target) / 604800000);
}
Source:Taco van den Broek
资料来源:Taco van den Broek
If you're not into extending prototypes, then here's a function:
如果您不想扩展原型,那么这里有一个函数:
function getWeek(date) {
if (!(date instanceof Date)) date = new Date();
// ISO week date weeks start on Monday, so correct the day number
var nDay = (date.getDay() + 6) % 7;
// ISO 8601 states that week 1 is the week with the first Thursday of that year
// Set the target date to the Thursday in the target week
date.setDate(date.getDate() - nDay + 3);
// Store the millisecond value of the target date
var n1stThursday = date.valueOf();
// Set the target to the first Thursday of the year
// First, set the target to January 1st
date.setMonth(0, 1);
// Not a Thursday? Correct the date to the next Thursday
if (date.getDay() !== 4) {
date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
}
// The week number is the number of weeks between the first Thursday of the year
// and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
Sample usage:
示例用法:
getWeek(); // Returns 37 (or whatever the current week is)
getWeek(new Date('Jan 2, 2011')); // Returns 52
getWeek(new Date('Jan 1, 2016')); // Returns 53
getWeek(new Date('Jan 4, 2016')); // Returns 1
回答by Balu Ertl
I found useful the Java SE's SimpleDateFormatclass described on Oracle's specification: http://goo.gl/7MbCh5. In my case in Google Apps Script it worked like this:
我发现Oracle 规范中描述的 Java SE 的SimpleDateFormat类很有用:http: //goo.gl/7MbCh5。就我而言,在 Google Apps Script 中,它的工作方式如下:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
Logger.log(weekNum);
}
For example in a spreadsheet macro you can retrieve the actual timezone of the file:
例如,在电子表格宏中,您可以检索文件的实际时区:
function getWeekNumber() {
var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
Logger.log(weekNum);
}