Javascript 获取本月的第几周
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3280323/
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 the month
提问by Prasad
How can i get the week number of month using javascript / jquery?
如何使用 javascript/jquery 获取月份的周数?
For ex.:
例如:
First Week: 5th July, 2010. / Week Number = First monday
第一周:2010 年 7 月 5 日。/周数 =第一个星期一
Previous Week: 12th July, 2010. / Week Number = Second monday
前一周:2010 年 7 月 12 日。/周数 =第二个星期一
Current Date: 19th July, 2010. / Week Number = Third Monday
当前日期:2010 年 7 月 19 日。/周数 =第三个星期一
Next week: 26th July, 2010. / Week Number = Last monday
下周:2010 年 7 月 26 日。/周数 =上周一
采纳答案by James
function weekAndDay(date) {
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'],
prefixes = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];
return prefixes[Math.floor(date.getDate() / 7)] + ' ' + days[date.getDay()];
}
console.log( weekAndDay(new Date(2010,7-1, 5)) ); // => "First Monday"
console.log( weekAndDay(new Date(2010,7-1,12)) ); // => "Second Monday"
console.log( weekAndDay(new Date(2010,7-1,19)) ); // => "Third Monday"
console.log( weekAndDay(new Date(2010,7-1,26)) ); // => "Fourth Monday"
console.log( weekAndDay(new Date()) );
Adding the capability to have Last ...may take some more hacking...
添加拥有的功能Last ...可能需要更多的黑客攻击......
回答by Olson.dev
This is an old question but the answers that exist are just plain wrong. This is my cross-browser compatible solution:
这是一个古老的问题,但现有的答案完全是错误的。这是我的跨浏览器兼容解决方案:
Date.prototype.getWeekOfMonth = function(exact) {
var month = this.getMonth()
, year = this.getFullYear()
, firstWeekday = new Date(year, month, 1).getDay()
, lastDateOfMonth = new Date(year, month + 1, 0).getDate()
, offsetDate = this.getDate() + firstWeekday - 1
, index = 1 // start index at 0 or 1, your choice
, weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7)
, week = index + Math.floor(offsetDate / 7)
;
if (exact || week < 2 + index) return week;
return week === weeksInMonth ? index + 5 : week;
};
// Simple helper to parse YYYY-MM-DD as local
function parseISOAsLocal(s){
var b = s.split(/\D/);
return new Date(b[0],b[1]-1,b[2]);
}
// Tests
console.log('Date Exact|expected not exact|expected');
[ ['2013-02-01', 1, 1],['2013-02-05', 2, 2],['2013-02-14', 3, 3],
['2013-02-23', 4, 4],['2013-02-24', 5, 6],['2013-02-28', 5, 6],
['2013-03-01', 1, 1],['2013-03-02', 1, 1],['2013-03-03', 2, 2],
['2013-03-15', 3, 3],['2013-03-17', 4, 4],['2013-03-23', 4, 4],
['2013-03-24', 5, 5],['2013-03-30', 5, 5],['2013-03-31', 6, 6]
].forEach(function(test){
var d = parseISOAsLocal(test[0])
console.log(test[0] + ' ' +
d.getWeekOfMonth(true) + '|' + test[1] + ' ' +
d.getWeekOfMonth() + '|' + test[2]);
});
You don't need to put it directly on the prototype if you don't want to. In my implementation, 6 means "Last", not "Sixth". If you want it to always return the actual week of the month, just pass true.
如果你不想,你不需要直接把它放在原型上。在我的实现中,6 表示“最后一个”,而不是“第六个”。如果您希望它始终返回本月的实际周数,只需通过true。
EDIT:Fixed this to handle 5 & 6-week months. My "unit tests", feel free to fork: http://jsfiddle.net/OlsonDev/5mXF6/1/.
编辑:修复此问题以处理 5 和 6 周的月份。我的“单元测试”,请随意分叉:http: //jsfiddle.net/OlsonDev/5mXF6/1/。
回答by Lord Midi
Having struggle with this topic too - thanks to Olson.dev! I've shortened his function a little bit, if somebody is interessted:
在这个话题上也有挣扎 - 感谢 Olson.dev!如果有人感兴趣,我已经缩短了他的功能:
// returns week of the month starting with 0
Date.prototype.getWeekOfMonth = function() {
var firstWeekday = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
var offsetDate = this.getDate() + firstWeekday - 1;
return Math.floor(offsetDate / 7);
}
update: if you need a localized version - you have to tweak the firstWeekday variable
更新:如果您需要本地化版本 - 您必须调整 firstWeekday 变量
// german version - week starts with monday
Date.prototype.getWeekOfMonth = function() {
var firstWeekday = new Date(this.getFullYear(), this.getMonth(), 1).getDay() - 1;
if (firstWeekday < 0) firstWeekday = 6;
var offsetDate = this.getDate() + firstWeekday - 1;
return Math.floor(offsetDate / 7);
}
回答by Chris Dixon
This is a few years on, but I've needed to use this functionality recently and, for certain dates in years 2016/2020 (such as January 31st), none of the code here works.
这是几年过去了,但我最近需要使用此功能,并且在 2016/2020 年的某些日期(例如 1 月 31 日),这里的代码都不起作用。
It's not the most efficient by any means, but hopefully this helps someone out as it's the only thing I could get working for those years along with every other year.
无论如何,这都不是最有效的,但希望这对某人有所帮助,因为这是我每隔一年就能工作的唯一方法。
Date.prototype.getWeekOfMonth = function () {
var dayOfMonth = this.getDay();
var month = this.getMonth();
var year = this.getFullYear();
var checkDate = new Date(year, month, this.getDate());
var checkDateTime = checkDate.getTime();
var currentWeek = 0;
for (var i = 1; i < 32; i++) {
var loopDate = new Date(year, month, i);
if (loopDate.getDay() == dayOfMonth) {
currentWeek++;
}
if (loopDate.getTime() == checkDateTime) {
return currentWeek;
}
}
};
回答by Ishaan Puniani
week_number = 0 | new Date().getDate() / 7
回答by Mow
function getWeekOfMonth(date) {
const startWeekDayIndex = 1; // 1 MonthDay 0 Sundays
const firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
const firstDay = firstDate.getDay();
let weekNumber = Math.ceil((date.getDate() + firstDay) / 7);
if (startWeekDayIndex === 1) {
if (date.getDay() === 0 && date.getDate() > 1) {
weekNumber -= 1;
}
if (firstDate.getDate() === 1 && firstDay === 0 && date.getDate() > 1) {
weekNumber += 1;
}
}
return weekNumber;
}
I hope this works Tested until 2025
我希望这有效 测试到 2025 年
回答by Eric
I think this works. It returns the week of the month, starting at 0:
我认为这有效。它返回一个月中的第几周,从 0 开始:
var d = new Date();
var date = d.getDate();
var day = d.getDay();
var weekOfMonth = Math.ceil((date - 1 - day) / 7);
回答by Johnny Rockex
function weekNumberForDate(date){
var janOne = new Date(date.getFullYear(),0,1);
var _date = new Date(date.getFullYear(),date.getMonth(),date.getDate());
var yearDay = ((_date - janOne + 1) / 86400000);//60 * 60 * 24 * 1000
var day = janOne.getUTCDay();
if (day<4){yearDay+=day;}
var week = Math.ceil(yearDay/7);
return week;
}
Apparently the first week of the year is the week that contains that year's first Thursday.
显然,一年中的第一周是包含该年第一个星期四的那一周。
Without calculating the UTCDay, the returned week was one week shy of what it should have been. Not confident this can't be improved, but seems to work for now.
在不计算 UTCDay 的情况下,返回的一周比应有的周数少了一周。不确定这无法改善,但现在似乎有效。
回答by dxh
This is nothing natively supported.
这不是本机支持的。
You could roll your own function for this, working from the first day of the month
您可以为此推出自己的功能,从每月的第一天开始工作
var currentDate = new Date();
var firstDayOfMonth = new Date( currentDate.getFullYear(), currentDate.getMonth(), 1 );
And then getting the weekday of that date:
然后获取该日期的工作日:
var firstWeekday = firstDayOfMonth.getDay();
... which will give you a zero-based index, from 0-6, where 0 is Sunday.
...这将为您提供一个从 0 开始的索引,从 0 到 6,其中 0 是星期日。
回答by Prasad
I was just able to figure out a easier code for calculate the number of weeks for a given month of an year ..
我只是想出了一个更简单的代码来计算一年中给定月份的周数..
y == year for example { 2012 } m == is a value from { 0 - 11 }
y == 年例如 { 2012 } m == 是从 { 0 - 11 } 的值
function weeks_Of_Month( y, m ) {
var first = new Date(y, m,1).getDay();
var last = 32 - new Date(y, m, 32).getDate();
// logic to calculate number of weeks for the current month
return Math.ceil( (first + last)/7 );
}
回答by user3473474
I think you want to use weekOfMonthso it will give 1-4 or 1-5 week of month. I solved the same problem with this:
我认为您想使用weekOfMonth它会在一个月中提供 1-4 或 1-5 周的时间。我用这个解决了同样的问题:
var dated = new Date();
var weekOfMonth = (0 | dated.getDate() / 7)+1;

