Reputation: 1171
Using javascript
I need to get the next upcoming date that matches a particular pattern.
The date I need is a Sunday and I can get the next Sunday like this:
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);
But the Sunday I need to get, is every other Sunday matching the following pattern.
10/20/18 11/03/18 11/17/18 12/01/18 12/15/18
Upvotes: 1
Views: 640
Reputation: 1171
This is what I came up with using just javascript. There is probably a better more efficient way of doing it.
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);
I can get the date I need by accessing the last item in the returned array
Upvotes: 0
Reputation: 2309
using momentjs it's easy like this:
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
http://momentjs.com/docs/#/get-set/day/
if you need a JS Date object:
moment().day(7).toDate()
Upvotes: 2