Javascript 用Javascript显示周数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7765767/
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
Show week number with Javascript?
提问by dannymcc
I have the following code that is used to show the name of the current day, followed by a set phrase.
我有以下代码用于显示当天的名称,后跟固定短语。
<script type="text/javascript">
<!--
// Array of day names
var dayNames = new Array(
"It's Sunday, the weekend is nearly over",
"Yay! Another Monday",
"Hello Tuesday, at least you're not Monday",
"It's Wednesday. Halfway through the week already",
"It's Thursday.",
"It's Friday - Hurray for the weekend",
"Saturday Night Fever");
var now = new Date();
document.write(dayNames[now.getDay()] + ".");
// -->
</script>
What I would like to do is have the current week number in brackets after the phrase. I have found the following code:
我想要做的是在短语后面的括号中包含当前周数。我发现了以下代码:
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
Which was taken from http://javascript.about.com/library/blweekyear.htmbut I have no idea how to add it to existing javascript code.
取自http://javascript.about.com/library/blweekyear.htm但我不知道如何将它添加到现有的 javascript 代码中。
回答by laurent
Simply add it to your current code, then call (new Date()).getWeek()
只需将其添加到您当前的代码中,然后调用 (new Date()).getWeek()
<script>
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var weekNumber = (new Date()).getWeek();
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var now = new Date();
document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>
回答by corolla
In case you already use jquery-ui (specifically datepicker):
如果您已经使用 jquery-ui(特别是 datepicker):
Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }
Usage:
用法:
var myDate = new Date();
myDate.getWeek();
More here: UI/Datepicker/iso8601Week
更多信息: UI/Datepicker/iso8601Week
I realize this isn't a general solution as it incurs a dependency. However, considering the popularity of jquery-ui this might just be a simple fit for someone - as it was for me.
我意识到这不是一个通用的解决方案,因为它会产生依赖性。然而,考虑到 jquery-ui 的流行,这可能只是一个简单的适合某人 - 就像对我一样。
回答by Agustin Haller
Consider using my implementation of "Date.prototype.getWeek", think is more accurate than the others i have seen here :)
考虑使用我的“Date.prototype.getWeek”实现,认为比我在这里看到的其他人更准确:)
Date.prototype.getWeek = function(){
// We have to compare against the first monday of the year not the 01/01
// 60*60*24*1000 = 86400000
// 'onejan_next_monday_time' reffers to the miliseconds of the next monday after 01/01
var day_miliseconds = 86400000,
onejan = new Date(this.getFullYear(),0,1,0,0,0),
onejan_day = (onejan.getDay()==0) ? 7 : onejan.getDay(),
days_for_next_monday = (8-onejan_day),
onejan_next_monday_time = onejan.getTime() + (days_for_next_monday * day_miliseconds),
// If one jan is not a monday, get the first monday of the year
first_monday_year_time = (onejan_day>1) ? onejan_next_monday_time : onejan.getTime(),
this_date = new Date(this.getFullYear(), this.getMonth(),this.getDate(),0,0,0),// This at 00:00:00
this_time = this_date.getTime(),
days_from_first_monday = Math.round(((this_time - first_monday_year_time) / day_miliseconds));
var first_monday_year = new Date(first_monday_year_time);
// We add 1 to "days_from_first_monday" because if "days_from_first_monday" is *7,
// then 7/7 = 1, and as we are 7 days from first monday,
// we should be in week number 2 instead of week number 1 (7/7=1)
// We consider week number as 52 when "days_from_first_monday" is lower than 0,
// that means the actual week started before the first monday so that means we are on the firsts
// days of the year (ex: we are on Friday 01/01, then "days_from_first_monday"=-3,
// so friday 01/01 is part of week number 52 from past year)
// "days_from_first_monday<=364" because (364+1)/7 == 52, if we are on day 365, then (365+1)/7 >= 52 (Math.ceil(366/7)=53) and thats wrong
return (days_from_first_monday>=0 && days_from_first_monday<364) ? Math.ceil((days_from_first_monday+1)/7) : 52;
}
You can check my public repo here https://bitbucket.org/agustinhaller/date.getweek(Tests included)
你可以在这里查看我的公共仓库https://bitbucket.org/agustinhaller/date.getweek(包括测试)
回答by hakunin
If you want something that works and is future-proof, use a library like MomentJS.
如果您想要一些有效且面向未来的东西,请使用像 MomentJS 这样的库。
moment(date).week();
moment(date).isoWeek()
回答by Martin Schilliger
It looks like this function I found at weeknumber.netis pretty accurate and easy to use.
看起来我在weeknumber.net上找到的这个函数非常准确且易于使用。
// This script is released to the public domain and may be used, modified and
// distributed without restrictions. Attribution not necessary but appreciated.
// Source: http://weeknumber.net/how-to/javascript
// Returns the ISO week of the date.
Date.prototype.getWeek = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), 0, 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
If you're lucky like me and need to find the week number of the month a little adjust will do it:
如果你像我一样幸运并且需要找到一个月的周数,稍微调整一下就可以了:
// Returns the week in the month of the date.
Date.prototype.getWeekOfMonth = function() {
var date = new Date(this.getTime());
date.setHours(0, 0, 0, 0);
// Thursday in current week decides the year.
date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
// January 4 is always in week 1.
var week1 = new Date(date.getFullYear(), date.getMonth(), 4);
// Adjust to Thursday in week 1 and count number of weeks from date to week1.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
}
回答by rebpp
All the proposed approaches may give wrong results because they don't take into account summer/winter time changes. Rather than calculating the number of days between two dates using the constant of 86'400'000 milliseconds, it is better to use an approach like the following one:
所有提议的方法都可能给出错误的结果,因为它们没有考虑夏季/冬季时间的变化。与其使用常数 86'400'000 毫秒计算两个日期之间的天数,不如使用如下方法:
getDaysDiff = function (dateObject0, dateObject1) {
if (dateObject0 >= dateObject1) return 0;
var d = new Date(dateObject0.getTime());
var nd = 0;
while (d <= dateObject1) {
d.setDate(d.getDate() + 1);
nd++;
}
return nd-1;
};
回答by Martijn B
By adding the snippet you extend the Date object.
通过添加代码片段,您可以扩展 Date 对象。
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.
如果您想在多个页面中使用它,您可以将其添加到一个单独的 js 文件中,该文件必须在其他脚本执行之前首先加载。对于其他脚本,我指的是使用 getWeek() 方法的脚本。
回答by Gabriel Furstenheim
If you already use Angular, then you could profit $filter('date')
.
如果您已经在使用 Angular,那么您可以从中获利$filter('date')
。
For example:
例如:
var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');
回答by Endless
I was coding in the dark (a challenge) and couldn't lookup or test my code.
我在黑暗中编码(一个挑战),无法查找或测试我的代码。
I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code.
我忘记了叫什么 (Math.celi) 所以我想特别确定我做对了,并想出了这个代码。
var elm = document.createElement('input')
elm.type = 'week'
elm.valueAsDate = new Date()
var week = elm.value.split('W').pop()
console.log(week)
But still i recommend any other solution that isn't required by the DOM.
但我仍然推荐 DOM 不需要的任何其他解决方案。
回答by Alex K.
With that code you can simply;
使用该代码,您可以简单地;
document.write(dayNames[now.getDay()] + " (" + now.getWeek() + ").");
(You will need to paste the getWeek
function above your current script)
(您需要将该getWeek
函数粘贴到当前脚本之上)