在 Javascript 中,我如何获得一个月的周数?我似乎在任何地方都找不到此代码.
In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.
我需要这个才能知道给定月份我需要多少行.
I need this to be able to know how many rows I need for a given month.
更具体地说,我想要一周中至少有一天的周数(一周被定义为从周日开始到周六结束).
To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).
所以,对于这样的事情,我想知道它有 5 周:
So, for something like this, I would want to know it has 5 weeks:
S M T W R F S
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
感谢大家的帮助.
每周从星期日开始
即使 2 月不是周日开始,这也应该可以工作.
This ought to work even when February doesn't start on Sunday.
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
每周从星期一开始
function weekCount(year, month_number) {
// month_number is in the range 1..12
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate();
return Math.ceil( used / 7);
}
一周从新的一天开始
function weekCount(year, month_number, startDayOfWeek) {
// month_number is in the range 1..12
// Get the first day of week week day (0: Sunday, 1: Monday, ...)
var firstDayOfWeek = startDayOfWeek || 0;
var firstOfMonth = new Date(year, month_number-1, 1);
var lastOfMonth = new Date(year, month_number, 0);
var numberOfDaysInMonth = lastOfMonth.getDate();
var firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7;
var used = firstWeekDay + numberOfDaysInMonth;
return Math.ceil( used / 7);
}
这篇关于通过 Javascript 获取每月的星期数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!