• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

通过 Javascript 获取每月的星期数

用户头像
it1352
帮助1

问题说明

在 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 

感谢大家的帮助.

正确答案

#1

每周从星期日开始

即使 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);
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanghfief
系列文章
更多 icon
同类精品
更多 icon
继续加载