js获取当前一周,当月的日期
要获取当前一周的日期,可以使用以下代码:
function getDatesOfCurrentWeek() {
const today = new Date();
const currentDayOfWeek = today.getDay(); // 0 (Sunday) - 6 (Saturday)
let startDate = new Date(today);
let endDate = new Date(today);
// 调整为星期日开始
startDate.setDate(startDate.getDate() - (currentDayOfWeek - 1));
endDate.setDate(endDate.getDate() + (7 - currentDayOfWeek));
// 创建日期数组
let dates = [];
for (let i = 0; i < 7; i++) {
dates.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return dates;
}
const datesOfCurrentWeek = getDatesOfCurrentWeek();
datesOfCurrentWeek.forEach(date => console.log(date.toLocaleDateString()));
要获取当前月份的日期,可以使用以下代码:
function getDatesOfCurrentMonth() {
const today = new Date();
const numberOfDaysInMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
let dates = [];
for (let day = 1; day <= numberOfDaysInMonth; day++) {
dates.push(new Date(today.getFullYear(), today.getMonth(), day));
}
return dates;
}
const datesOfCurrentMonth = getDatesOfCurrentMonth();
datesOfCurrentMonth.forEach(date => console.log(date.toLocaleDateString()));
这两个函数会返回一个日期数组,你可以通过toLocaleDateString()
方法将日期格式化为易读的格式,也可以根据需要自定义格式化方法。
评论已关闭