需注意Date()中的月是从0开始的

  • 根据年月取周数和周一到周五的日期
    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
    32
    33
    34
    35
    36
    37
    	/**
    * 根据年月取周数和周一到周五的日期
    * @param year
    * @param month
    */
    function getInfo(year, month) {
    var result=[];
    var d = new Date();
    // what day is first day
    d.setFullYear(year, month-1, 1);
    var w1 = d.getDay();
    if (w1 == 0) w1 = 7;
    // total day of month
    d.setFullYear(year, month, 0);
    var dd = d.getDate();
    // first Monday
    var d1,week_count;
    if (w1 != 1) d1 = 7 - w1 + 2;
    else d1 = 1;
    week_count = Math.ceil((dd-d1+1)/7);//周数
    result[0]=week_count;
    // document.write(year + "年" + month + "月有" + week_count +"周");
    for (var i = 0; i < week_count; i++) {
    var monday = d1+i*7;
    var sunday = monday + 6;
    var from = year+"/"+month+"/"+monday;
    var to;
    if (sunday <= dd) {
    to = year+"/"+month+"/"+sunday;
    } else {
    d.setFullYear(year, month-1, sunday);
    to = d.getFullYear()+"/"+(d.getMonth()+1)+"/"+d.getDate();
    }
    document.write("第"+(i+1)+"周 从" + from + " 到 " + to + "");
    }
    return result;
    }
  • 根据年月日判断是一年中的第几周
    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
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    /**
    * 判断年份是否为润年
    *
    * @param {Number} year
    */
    function isLeapYear(year) {
    return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
    }
    /**
    * 获取某一年份的某一月份的天数
    *
    * @param {Number} year
    * @param {Number} month
    */
    function getMonthDays(year, month) {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
    }
    /**
    * 获取某年的某天是第几周
    * @param {Number} y
    * @param {Number} m
    * @param {Number} d
    * @returns {Number}
    */
    function getWeekNumber(y, m, d) {
    var now = new Date(y, m - 1, d),
    year = now.getFullYear(),
    month = now.getMonth(),
    days = now.getDate();
    //那一天是那一年中的第多少天
    for (var i = 0; i < month; i++) {
    days += getMonthDays(year, i);
    }

    //那一年第一天是星期几
    var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

    var week = null;
    if (yearFirstDay == 1) {
    week = Math.ceil(days / yearFirstDay);
    } else {
    days -= (7 - yearFirstDay + 1);
    week = Math.ceil(days / 7) + 1;
    }

    return week;
    }