如何使用javascript获取特定年/月的周数?

时间:2013-11-05 15:32:56

标签: javascript cordova calendar

对于Ex: 2013年11月的周数 45到49 2014年12月的周数 49到53

1 个答案:

答案 0 :(得分:0)

这是德国/欧洲/ ISO周的解决方案。

  1. 查找给定日期的星期四。星期四确定所请求的一周所属的年份
  2. 查找当年1月4日当周的星期四。本周四是第1周
  3. 计算当前周的周四与周一的周四之间的周差加一...这将是给定日期的周数
  4. 试试这个

    function thursday(mydate) {
      var Th=new Date();
      Th.setTime(mydate.getTime() + (3-((mydate.getDay()+6) % 7)) * 86400000);
      return Th;
    }
    
    function getCalWeek(y, m, d) {
        thedate=new Date(y, m-1, d);
        ThursDate=thursday(thedate);
        weekYear=ThursDate.getFullYear();
        ThursWeek1=thursday(new Date(weekYear,0,4));
        theweek=Math.floor(1.5+(ThursDate.getTime()-ThursWeek1.getTime())/86400000/7);
        return theweek;
    }
    
    console.log("The week of the given date is: " + getCalWeek(2013, 11, 5));
    

    编辑:对于您的具体问题,您需要给出月份和年份,然后计算周数

    function daysInMonth(month,year) {
        var m = [31,28,31,30,31,30,31,31,30,31,30,31];
        if (month != 2) return m[month - 1];
        if (year%4 != 0) return m[1];
        if (year%100 == 0 && year%400 != 0) return m[1];
        return m[1] + 1;
    }
    
    function getWeekRange(m, y) {
        var startWeek = getCalWeek(y, m, 1);
        var endWeek = getCalWeek(y, m, daysInMonth(m, y));
        return startWeek + " to " + endWeek;
    }