admin管理员组

文章数量:1180552

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?

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%}

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?

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%}

Share Improve this question edited Sep 23, 2022 at 3:49 mikemaccana 123k110 gold badges427 silver badges529 bronze badges asked Mar 24, 2017 at 20:12 AJ_AJ_ 3,97711 gold badges50 silver badges83 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 14

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)));

You can use Moment.js library - utility library for dates/time operations

Here's examplary code to get current week's dates starting from monday:

function getThisWeekDates() {
  var weekDates= []; 

  for (var i = 1; i <= 7; i++) {
    weekDates.push(moment().day(i)); 
  }

  return weekDates; 
}

var thisWeekDates = getThisWeekDates();

thisWeekDates.forEach(function(date){ console.log(date.format());});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

The code above prints following results to the console:

2017-03-20T21:26:27+01:00
2017-03-21T21:26:27+01:00
2017-03-22T21:26:27+01:00
2017-03-23T21:26:27+01:00
2017-03-24T21:26:27+01:00
2017-03-25T21:26:27+01:00
2017-03-26T21:26:27+02:00

I will trace your code using your example of Feb 27, 2017:

first = 27 - 1 + 1 = 27

loop:

Feb.setDate(27) = 27 feb
Feb.setDate(28) = 28 feb
Feb.setDate(29) = Not 29 days in Feb. So it sets current to 29-28 = 1st day of March
March.setDate(30) = March 30
March.setDate(31) = March 31     
March.setDate(32) = Not 32 days in March. So it sets current to 31-32 = 1st of April..
April.setDate(33) = Not 33 days in April. So it sets current day 33-30 = 3rd day of May. 

Please note that I used the shorthand of Month.setDate() to show the month of the current Date object when it was being called.

So the issue is with your understanding of setDate that is being used on current. It changes the month and if the value you use isn't a day in the month it adjusts the month and day appropriately. I hope this cleared things up for you.

For how to add one to a date, see Add +1 to current date. Adapted to your code, you can set current to the first day of the week then just keep adding 1 day and pushing copies to the array:

function days(current) {
  var week = [];
  // Starting Monday not Sunday 
  var first = current.getDate() - current.getDay() + 1;
  current.setDate(first);
  for (var i = 0; i < 7; i++) {
    week.push(new Date(+current));
    current.setDate(current.getDate()+1);
  }
  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()));

Note that this changes the date passed in (per the original code), you may want to make current a copy to avoid that.

Suppose monday starts the week, you can calculate monday and go to sunday. getDategives you the day of the week, and Sunday starts at 0. With momnday, we get just offset forward to 6 days to get sunday

mondayThisWeek(date: Date): Date {
  const d = new Date(date)
  const day = d.getDay()
  const diff = d.getDate() - day + (day === 0 ? -6 : 1)
  return new Date(d.setDate(diff))
}

const offsetDate = (base: Date, count: number): Date => {
  const date = new Date(base)
  date.setDate(base.getDate() + count)
  return date
}

thisWeek(today: Date): TimeRange {
  const monday = mondayThisWeek(today)
  return {
    startDate: monday,
    endDate: offsetDate(monday, 6)
  }
}

This can be achieved easly using moment

const getWeekDates = () => {

  let weekDates = [];

  for (let i = 0; i < 7; i++)
    weekDates.push(moment().add(i, 'd'));

  return weekDates;
};


console.log(getWeekDates());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

本文标签: javascriptGet all days of the week given a dayStack Overflow