gpt4 book ai didi

javascript - 如何使用javascript中的日期获取特定月份的周数

转载 作者:行者123 更新时间:2023-12-03 02:45:37 24 4
gpt4 key购买 nike

这是我的代码

const date = new Date();
const startDate = new Date(date.getFullYear(), date.getMonth(), 1);
const endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);

const getDateArray = function(start, end) {
const arr = [];
const dt = new Date(start);
while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}
return arr;
}
const dateArr = getDateArray(startDate, endDate);

在上面的代码中,我得到了当前月份日期列表dateArr,现在我需要按周对天进行分组,从周列表中我只需要过滤周开始日期和周末日期必须在列表格式中我尝试了上面的代码,但我无法继续下一步。

最佳答案

这有效。

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;
}

关于javascript - 如何使用javascript中的日期获取特定月份的周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48108740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com