skip to Main Content
<script>
var startDate = "2023/04/01";
var endDate = "2023/04/16";
var dateMove = new Date(startDate);
var strDate = startDate;    
while (strDate < endDate){
    var strDate = dateMove.toISOString().slice(0,10);
    array.push(strDate);
    dateMove.setDate(dateMove.getDate()+1);         
};
$('.show').html(array);
</script>
result"2023/04/01","2023/04/01","2023/04/02","2023/04/03","2023/04/04","2023/04/05","2023/04/06","2023/04/07","2023/04/08","2023/04/09","2023/04/10","2023/04/11","2023/04/12","2023/04/13","2023/04/14","2023/04/15","2023/04/16"

how to get results on Sundays 2023/04/02,2023/04/09,2023/04/16

4

Answers


  1. Study the following code and look up the functions that it uses in the documentation of the Date object.

    var array = [];
    for (var d = new Date("2023-04-01");
      d <= new Date("2023-04-16");
      d.setUTCDate(d.getUTCDate() + 1))
      if (d.getUTCDay() === 0)
        array.push(d.toISOString().substring(0, 10));
    document.body.textContent = array;
    Login or Signup to reply.
  2. You could calculate the first Sunday from the start date, then loop while adding 7 to the date each time. (There is no need to go through every single day in the range just to find Sundays.)

    let startDate = "2023/04/01";
    let endDate = "2023/04/16";
    let curr = new Date(startDate), end = new Date(endDate);
    curr.setDate(curr.getDate() + (7 - curr.getDay()) % 7);
    let res = [];
    for (; curr <= end; curr.setDate(curr.getDate() + 7)) 
      res.push(curr.toLocaleDateString('en-ZA'));
    console.log(res);
    Login or Signup to reply.
  3. You can do like following. 1. Set the start and end dates. 2. Loop through each day from the start date to the end date. 3. Check if the current day is a Sunday (Sunday = 0, Monday = 1, etc.) and push it to the sudays array. Important – you should increase currentDate in the loop.

        const startDate = new Date("2023/04/01");
        const endDate = new Date("2023/04/16");
    
        let currentDate = startDate;
        let sundays = [];
        while (currentDate <= endDate) {
          if (currentDate.getDay() === 0) {
            sundays.push(currentDate.toLocaleDateString('en-ZA'));
          }
          currentDate.setDate(currentDate.getDate() + 1);
        }
    
        console.log(sundays);
    Login or Signup to reply.
  4. You can do:

    const startDate = new Date('2023/04/01')
    const endDate = new Date('2023/04/16')
    const sundays = []
    
    for (let d = startDate; d <= endDate; d.setDate(d.getDate() + 1))
      !d.getDay() && sundays.push(new Date(d).toLocaleDateString('en-ZA'))
    
    console.log(sundays)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search