0

Get range of week dates based on given date

currentDate = moment().date();
// 19

Is it possible to get range of week days in an array, like so?

[16,17,18,19,20,21,22]

Is there is a short hand method or a known library I could use to achieve that?

Thanks

Deano
  • 11,582
  • 18
  • 69
  • 119
  • 1
    All of the functions exposed by moment are [documented on their website](http://momentjs.com/docs/). Asking for a library is specifically off-topic for Stack Overflow. – Heretic Monkey Jul 19 '17 at 12:29

4 Answers4

2

I don't know relevant library, but there is a way:

var currentDate = new Date; // get current date
var first = currentDate.getDate() - currentDate.getDay(); // First day
var last = first + 6; // last day
var list = [];
for (var i = first; i <= last; i++) {
    list.push(i);
}
list
> [16, 17, 18, 19, 20, 21, 22]
Andrey Lukyanenko
  • 3,679
  • 2
  • 18
  • 21
2

Here's something you can do:

function getWeekDaysByWeekNumber(num) {
    var week = moment().week(num);
    var weekDays = [];

    for(var idx=0; idx< 7; idx++) {
        weekDays.push(week.day(idx).date());
    }

    return weekDays;
}

I just tried it, and it seems to work fine.

Explanation:

  • week(num) method returns a moment object pointing to given week number. For instance week(20) would give me a date in 20th Week.

  • week.day(num) gives me given day (0-6) in the week, where 0 returns the Sunday and 6 returns the Saturday.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
0

Underscore.js has a range() function. Is that what you want? http://underscorejs.org/#range

You could do something like:

var RANGE_DISTANCE = 3;
var CENTER = 19;
_.range(CENTER - RANGE_DISTANCE, CENTER + RANGE_DISTANCE + 1)

Which you could abstract out to a function:

function generateRangeAroundCenter(var center, var range_distance) {
    return _.range(center-range_distance, center+range_distance+1);
}

Seems like overkill to import underscore just for that though.

I see some good examples of what you want here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?

There are examples that don't use libraries at all, like this. Let me know if that helps you out, or if you're looking for something else.

itsmichaelwang
  • 2,282
  • 4
  • 16
  • 25
0

The format used for the day ordering ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Can get the current weekday to the corresponding locale weekday using moment().day(). If today is Wednesday it will return 3.

Depending on these values you can calculate the rest of the days of week.

Charles
  • 1,008
  • 10
  • 21