如何使用java脚本中的日期来获取特定月份的周数

时间:2018-01-05 07:03:10

标签: javascript

这是我的代码

dateArr

在上面的代码中,我得到了当前月份日期列表{{1}},现在我需要将这些天数分组一周,从周列表中我只需要过滤周开始日期和必须在的周末日期list formate我尝试了上面的代码,但我不能继续下一步。

1 个答案:

答案 0 :(得分:0)

这很有效。

var date = new Date();
console.log("All Weeks : ", getWeeksInaMonth())
console.log("Current Week : ", getCurrentWeek())
console.log("Current and previous weeks : ",getCurrAndPrevWeeks())

function getFormattedDate(dateobj)
{
    var date = dateobj.getDate(), month = dateobj.getMonth()+1, year = dateobj.getFullYear();
    var formattddate = (date<10?"0":"")+date+"/"+(month<10?"0":"")+month+"/"+year;
    return formattddate;
}

function getWeeksInaMonth()
{
    var startdate = new Date(date.getFullYear(), date.getMonth(), 1); 
    var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
    var weeks = [];
    for(var i=1,n=enddate.getDate();i<n;)
    {
        startdate.setDate(i);
        var arr = [getFormattedDate(startdate)];
        i =i+ 6-startdate.getDay();
        if(i>n) i=i-(i-n);
        startdate.setDate(i);
        arr.push(getFormattedDate(startdate));
        i++;
        weeks.push(arr);
    }
    return weeks
}

function getCurrentWeek()
{
    var today = new Date(), day = today.getDay();
    return [getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()-day)),
            getFormattedDate(new Date(today.getFullYear(),today.getMonth(),today.getDate()+6-day))];
}

function getCurrAndPrevWeeks()
{
    var startdate = new Date(date.getFullYear(), date.getMonth(), 1); 
    var enddate = new Date(date.getFullYear(), date.getMonth()+1, 0);
    var today = new Date().getDate();
    var weeks = [];
    for(var i=1,n=enddate.getDate();i<n;)
    {
        startdate.setDate(i);
        var arr = [getFormattedDate(startdate)];
        i =i+ 6-startdate.getDay();
        if(i>n) i=i-(i-n);
        startdate.setDate(i);
        arr.push(getFormattedDate(startdate));
        weeks.push(arr);
        if(today>=i-6 && today<=i) break;
        i++;
    }
    return weeks;
}