Reputation: 792
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
Upvotes: 0
Views: 67
Reputation:
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
Upvotes: 3