0

I am implementing a chart to display the daily data. At the moment I can only write the static data like.

data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

How can I write a function to get this starting from current day and time.

Any help is appreciated. Thank you

surazzarus
  • 772
  • 5
  • 17
  • 32
  • 1
    Use [`moment.js`](https://momentjs.com) with its wide range of functions (e.g. [start-of](http://momentjs.com/docs/#/manipulating/start-of/)) – ssc-hrep3 Jul 31 '18 at 14:40
  • [`Date.prototype.getDay()` - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay): _"The `.getDay()` method returns the day of the week for the specified date according to local time, where 0 represents Sunday."_ – Andreas Jul 31 '18 at 14:43
  • Possible duplicate of [How to get the day of the week from the day number in Javascript?](https://stackoverflow.com/questions/9677757/how-to-get-the-day-of-the-week-from-the-day-number-in-javascript) – Andreas Jul 31 '18 at 14:46

1 Answers1

3

This function here will populate an array over and over again with days Mon..Sun n times starting from the current day of the week:

function populateDateArray(n = 7) {
    var daysInAWeek = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
    var returnValue = new Array(n);
    var currentDay = (new Date().getDay()); //0 = sunday
    for (var i = 0; i < n; i++) {
        returnValue[i] = daysInAWeek[(currentDay++) % 7];
    }
    return returnValue;
}

What we do is get the current day of the week by doing new Date().getDay() - this will return the date in numeric form (0 = sunday, 1 = monday.... 6 = saturday).

After this, we then iterate n times, grabbing daysInAWeek from the current day of the week + 1. This would usually cause overflow, so we will take the modulo 7 of this result which will bound the value between 0..6.

As a result, when we get to saturday it will then loop back to the start of daysInAWeek and go to sunday (and then over and over again).

Usage: var days = populateDateArray(28); //get 28 days from today

Adam Mellen
  • 240
  • 2
  • 6
  • Thanks for the working example.. Also if i have to make it work on hourly basis, do I have to do the similar stuff? – surazzarus Jul 31 '18 at 15:38
  • If you want to do it on an hourly basis (hours 1-24) you can do the same just by adding to the `daysInAWeek` array and then changing `% 7` to `% 24` (or, for a more generic case, `% daysInAWeek.length`) – Adam Mellen Jul 31 '18 at 17:45