使用javascript每隔一个星期获取与特定星期匹配的数据

使用javascript每隔一个星期获取与特定星期匹配的数据,javascript,Javascript,使用javascript我需要获得与特定模式匹配的下一个即将到来的日期 我需要的日期是星期天,我可以这样得到下一个星期天: const date = new Date(); const diff = date.getDay() - 7; if (diff > 0) { date.setDate(date.getDate() + 6); } else if (diff < 0) { date.setDate(date.getDate() + ((-1) * diff))

使用
javascript
我需要获得与特定模式匹配的下一个即将到来的日期

我需要的日期是星期天,我可以这样得到下一个星期天:

const date = new Date();
const diff = date.getDay() - 7;
if (diff > 0) {
    date.setDate(date.getDate() + 6);
} else if (diff < 0) {
    date.setDate(date.getDate() + ((-1) * diff));
}
console.log(date);
moment().day(-7) // returns last Sunday
moment().day(0) // returns this Sunday
moment().day(7) // returns next Sunday object
moment().day(14) // returns next+1 Sunday object
const date=新日期();
const diff=date.getDay()-7;
如果(差异>0){
date.setDate(date.getDate()+6);
}否则如果(差异<0){
date.setDate(date.getDate()+(-1)*diff));
}
控制台日志(日期);
但是我需要得到的星期天,是每隔一个星期天匹配以下模式的

2018年10月20日 11/03/18 11/17/18 12/01/18
2018年12月15日

使用momentjs很容易做到:

const date = new Date();
const diff = date.getDay() - 7;
if (diff > 0) {
    date.setDate(date.getDate() + 6);
} else if (diff < 0) {
    date.setDate(date.getDate() + ((-1) * diff));
}
console.log(date);
moment().day(-7) // returns last Sunday
moment().day(0) // returns this Sunday
moment().day(7) // returns next Sunday object
moment().day(14) // returns next+1 Sunday object

如果需要JS日期对象:

moment().day(7).toDate()

这就是我使用javascript时想到的。也许有一种更好更有效的方法

function getDateArray(start, end = new Date()) {
  const arr = new Array();
  const sd = new Date(start);
  while (sd <= end) {
    const d = new Date(sd);
    const d2 = new Date(d);
    d2.setDate(d2.getDate() + 13);
    const v = d.valueOf();
    const ds1 = d.toDateString();
    const ds2 = d2.toDateString();
    const obj = { label: `From: ${ds1} To: ${ds2}`, value: v };
    arr.push(obj);
    sd.setDate(sd.getDate() + 14);
  }
  return arr;
}

const today = new Date();
getDateArray('08/19/18', today);
函数getDateArray(开始,结束=新日期()){ const arr=新数组(); const sd=新日期(开始);
虽然(sd那么问题出在哪里呢?拿第一个并继续增加14天。但是你的模式中的天是星期六…我明白了,明白了。但也许增加一个momentjs不是问题。至少知道它有什么帮助会很好。我希望这是一个灰色区域。但是因为有这么多有用的库,我认为获得推荐是有帮助的也就是说,编程人员通常有时过于依赖库。