Ways to identify Sundays within a specified timeframe

<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 find the Sundays in the result: 2023/04/02,2023/04/09,2023/04/16

Answer №1

Explore the code snippet below and refer to the official documentation for details on the functions used with the Date object.

var list = [];
for (var date = new Date("2023-04-01");
  date <= new Date("2023-04-16");
  date.setUTCDate(date.getUTCDate() + 1))
  if (date.getUTCDay() === 0)
    list.push(date.toISOString().substring(0, 10));
document.body.textContent = list;

Answer №2

To find the first Sunday after the start date, you can simply add 7 days until you reach a Sunday. There is no need to iterate through each day in the range just to identify Sundays.

let start = "2024/02/15";
let end = "2024/03/01";
let current = new Date(start), finish = new Date(end);
current.setDate(current.getDate() + (7 - current.getDay()) % 7);
let result = [];
for (; current <= finish; current.setDate(current.getDate() + 7)) 
  result.push(current.toLocaleDateString('en-GB'));
console.log(result);

Answer №3

Here is a way to achieve this: 1. Define the start and end dates. 2. Iterate through each day between the start and end dates. 3. Determine if the current day is a Sunday (0 for Sunday, 1 for Monday, etc.) and add it to the sundays array. It is important to increment the currentDate within 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);

Answer №4

Here's a solution:

let start = new Date('2023-04-01');
let end = new Date('2023-04-16');
let sundays = [];

for (let date = start; date <= end; date.setDate(date.getDate() + 1)) {
  if (date.getDay() === 0) {
    sundays.push(new Date(date).toLocaleDateString('en-US'));
  }
}

console.log(sundays)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locating the source and reason behind the [object ErrorEvent] being triggered

I'm facing an issue where one of my tests is failing and the log is not providing any useful information, apart from indicating which test failed... LoginComponent should display username & password error message and not call login when passed no ...

Utilizing Angular: Filtering Views Based on JSON Data Values

I am struggling to figure out why a basic Angular filter is not working for me in this example. Despite following the recommended format I found online, it does not seem to be functioning properly. Essentially, I just need to display information from the a ...

Integration of Foundation-Apps Angular website with unit testing using Karma-Jasmine

While attempting to run a karma jasmine unit test, I encountered an issue with using angular-mocks and foundation-apps. It's possible that I overlooked something in my setup. I've provided an example project on github for further evaluation due t ...

Choose a row in an Angular ngGrid upon loading the page

My question is in relation to this inquiry How can I retrieve selected rows from ng-grid? Check out the plunker sample - http://plnkr.co/edit/DiDitL?p=preview Upon page load, I am looking to have a row pre-selected without relying on 'ngGridEventDa ...

Interactive links Navbar

My current project involves creating a dynamic Navbar that fetches data from mongodb. Here is the structure I am working with: # src * [components/] * [Navbar.js]] * [Layout.js]] * [pages/] * [index.js] * [_app.js] Unfortunately, it seems like I ...

I encountered an issue while working with Material-UI and Mobx. The error message reads: "Material-UI: capitalize(string) function requires a string argument

enter code hereI encountered this issue when I copied a React component from and the state of this component is managed by Mobx as shown below: @observable snackbarState = { open: false, vertical: null, horizontal: null, }; @action toggle ...

Emphasize entries in an index that match the currently visible content as you scroll

I have a table of contents in my HTML page with the CSS attribute position: fixed;. I want to emphasize the current reading position by highlighting it (bold or italics) as I scroll down the page. | yada yada yada ... 1. Secti ...

Exploring the possibilities of incorporating animation in model-viewer using a-frame examples

I am currently working on a project where I am looking to repurpose the following example: All I need to do is add a trigger that will start the animation on a click event. I have successfully set this up to run on my server by using the code from https: ...

The current registry configuration does not provide support for audit requests when running npm audit

I am facing an issue with one of my dependencies that is in the form of "protobufjs": "git+https://github.com/danieldanielecki/protobufjs-angularfire.git#master". I installed it using npm install --save https://github.com/danieldanielecki/protobufjs-angula ...

Exploring the concept of inheriting AngularJS modules

I am intrigued by the behavior of AngularJS. I am wondering if AngularJS modules inherit dependencies from other modules. Let's consider the following structure: var PVNServices = angular.module('PVN.services', []); PVNServices.factory(&a ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

What is the best way to include a property with a name in quotes to an object after it has already been declared?

Is there a way to include a property with a quoted name to an object after its declaration? Here's a simplified scenario: var Obj = {} Instead of: Obj.dog = "Woof!"; I want to achieve: Obj."dog" = "Woof!"; Similar to: var Obj = { "dog" : " ...

Delay calls to JavaScript functions, ensuring all are processed in order without any being discarded

Is there a way for a function to limit the frequency of its calls without discarding them? Instead of dropping calls that are too frequent, is it possible to queue them up and space them out over time, say X milliseconds apart? I've explored concepts ...

In Vue, applying CSS styles to D3's SVG elements may not work as expected when using the scoped attribute

Here is the code snippet of my component: <template> <div id="something" class="card"> </div> </template> const height = 200; const width = 200; let graph = d3 .select('#something') .append('svg') ...

Discrepancy in functionality between .show() and .append() methods within JQuery

I have a container with an ID of "poidiv" that is hidden (display: none) initially. My goal is to dynamically load this container multiple times using a loop, where the maximum value for the loop is not predetermined. I attempted to achieve this using jQue ...

How to determine the length of a JavaScript object

Would like help determining the length of the report_data(object) key using the provided code, but it seems to result in a value of 3. a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"} Object {report_freq: "daily", report_ite ...

What is the reason for the inclusion of [Circular] in the hash?

Below is the code snippet: db.query(str, arr, function selectCb(error, results, fields) { if (error) { return proceed(false, {errno:'010',message:error.message}, request); } var q = async.queue ...

Node.js: Retaining JSON objects with the highest value from duplicate entries

From an external source, I have imported JSON data containing various objects, some of which share the same ID value. For instance: { "ID": "1", "name": "Bob", "ink": "100" }, { "ID":&qu ...

How come the code functions when executed line by line, but fails to produce desired results when run as a complete script?

Whenever I try running this code in the Chrome Console, it results in an error Uncaught TypeError: Cannot read property 'playlist' of undefined var owner = "yamusic-trending" var kind = "1000" var url = `https://music.yandex.ru/handlers/pla ...

Could you please clarify the specific functionality of this script?

I've been trying to figure out the communication process between (a website that tracks real-time changes in Roblox's catalog and updates the client) and I came across this script while inspecting the site. It seems like this script is responsib ...