Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 21764  / 7 Years ago, fri, march 24, 2017, 12:00:00

I'm trying to make a function to get all the days of the week given the current day. I had a function that i thought was working until i noticed that if the day of the week is near the end of the month, like for example February, i get weird data. Anyone know whats going on and how to fix it?


Console




function days(current) {
var week = new Array();
// Starting Monday not Sunday
var first = ((current.getDate() - current.getDay()) + 1);
for (var i = 0; i < 7; i++) {
week.push(
new Date(current.setDate(first++))
);
}
return week;
}

var input = new Date(2017, 1, 27);
console.log('input: %s', input);

var result = days(input);
console.log(result.map(d => d.toString()));

.as-console-wrapper{min-height:100%}




More From » arrays

 Answers
23

If you don't want to use some kind of other library like Moment.js you can also change your function a little and then it will work. Try this:





function dates(current) {
var week= new Array();
// Starting Monday not Sunday
current.setDate((current.getDate() - current.getDay() +1));
for (var i = 0; i < 7; i++) {
week.push(
new Date(current)
);
current.setDate(current.getDate() +1);
}
return week;
}
console.log(dates(new Date(2017, 1, 27)));




[#58395] Thursday, March 23, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;