javascript - 获取未来三个月的周日列表
问题描述
我需要得到一份未来三个月的周日清单。我写了一个一直工作到今天的函数。从今天开始的三个月是一月,它是 0,所以我的 for 循环不起作用。
function getSundays(year) {
const offdays = [];
let i = -1;
const currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 90);
for ( let month = new Date().getMonth(); month < currentDate.getMonth(); month += 1) {
const tdays = new Date(year, month, 0).getDate();
for (let date = 1; date <= tdays; date += 1) {
const smonth = (month < 9) ? `0${month + 1}` : month + 1;
const sdate = (date < 10) ? `0${date}` : date;
const dd = `${year}-${smonth}-${sdate}`;
const day = new Date();
day.setDate(date);
day.setMonth(month);
day.setFullYear(year);
if (day.getDay() === 0 ) {
offdays[i += 1] = dd;
}
}
}
return offdays;
}
我怎样才能解决这个问题?
解决方案
你可以使用 Date get|setMonth 和 get|setDay 的方法,就像这样:
const next = new Date()
next.setMonth( (new Date()).getMonth()+1 )
const allSundays = []
const sundaysByMonth = []
for( let i = 0; i<3; i++ ){
const m = next.getMonth()
const sundays = []
for( let j = 0; j < 7; j++ ){
if ( next.getDay() == 0 ){
sundays.push( next.getDate() )
allSundays.push( next.getDate() )
next.setDate( next.getDate() + 6 ) // increment in 6 days not 7 (one week) because line below increase again
}
next.setDate( next.getDate() + 1 ) // increase month day until arrive in sunday
if( next.getMonth() != m ){ // check if not exceeded the month
sundaysByMonth.push( sundays )
break // break to go to next month
}
}
}
console.log( allSundays )
console.log( sundaysByMonth )
const el = document.getElementById("demo");
for( let i = 0; i < allSundays.length; i++ ){
const li = document.createElement('li')
li.innerHTML = 'Sunday '+ allSundays[i]+' '
el.appendChild(li)
}
<p>The getDay() method returns the weekday as a number:</p>
<ul id="demo"></ul>
推荐阅读
- python - 我有一个数字列表,我想知道某个数字之后出现的第一个数字
- reactjs - 如何从reducer中的数组中删除特定对象
- spring-boot - 根据jpa中的两个外国ID获取行
- c# - 带有 CMake 的 C# - 添加服务引用(wsdl 文件)
- node.js - 集成 Skype 和 facebook Messenger 没有用fulfillmenttext 响应
- hibernate - spring jpa - 基于配置文件调用存储过程
- spring-boot - How to configure Spring Data JPA to only read the schema?
- python - 使用一些沙箱或解释器执行简单但不受信任的 Python 代码
- kubernetes - 由于镜像拉取失败,Kubernetes 部署失败
- c - 将 sprintf 用于多个输入的更好方法是什么?