Obtaining an array of weeks for the previous two months from the current date using JavaScript

Looking to generate a list of weeks for the past two months using JavaScript. Any suggestions on how to accomplish this task would be greatly appreciated.

[   

    {
        "week_start": "8/01/2016",
        "week_end": "8/06/2016"
    }, {
        "week_start": "8/07/2016",
        "week_end": "8/13/2016"
    }, {
        "week_start": "8/14/2016",
        "week_end": "8/20/2016"
    }, {
        "week_start": "8/21/2016",
        "week_end": "8/27/2016"
    }, {
        "week_start": "8/28/2016",
        "week_end": "9/03/2016"
    }, {
        "week_start": "9/04/2016",
        "week_end": "9/10/2016"
    }, {
        "week_start": "9/11/2016",
        "week_end": "9/17/2016"
    }, {
        "week_start": "9/18/2016",
        "week_end": "9/24/2016"
    }, {
        "week_start": "9/25/2016",
        "week_end": "10/01/2016"
    }, {
        "week_start": "10/02/2016",
        "week_end": "10/08/2016"
    }


]

Answer №1

To utilize native JavaScript Date objects, follow this example:

// Create two Date objects to serve as the lower and upper bounds
const currentDate = new Date();
const twoMonthsAgo = new Date();
twoMonthsAgo.setMonth(twoMonthsAgo.getMonth() - 2);

// Helper function to increment the date by two weeks
const addTwoWeeks = (date) => {
  date.setDate(date.getDate() + 7);
};

// Helper function to display weeks in the desired format
const displayWeek = (date) => {
  var nextWeek = new Date(date);
  nextWeek.setDate(nextWeek.getDate() + 7);
  return {
    "week_start": date.toLocaleString('en-US').split(',').shift(),
    "week_end": nextWeek.toLocaleString('en-US').split(',').shift()
  }
};

let data = [];

// Iterate
for (let week = new Date(twoMonthsAgo); week < currentDate; addTwoWeeks(week)) {
  data.push(displayWeek(week));
}

document.getElementById('result').innerHTML = JSON.stringify(data, null, "\t");
<pre><code id="result"></code></pre>

Answer №2

If you're looking to implement date calculations in your code, check out http://momentjs.com/ for a helpful library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"> </script>
<script>
  var startDay = moment("2016-07-24"); // Sunday
  var results = [];
  for (var index = 1; index < 10; index++) {
      // console.log('week_start' + startDay.add(index, 'weeks').calendar());
      // console.log('week_end' + startDay.add(index, 'weeks').subtract(1, 'days').calendar());
      results.push({
        'week_start': startDay.add(index, 'weeks').calendar(),
        'week_end': startDay.add(index, 'weeks').subtract(1, 'days').calendar()
      })
  }
  console.log(results)
</script>

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

Utilize ES6 syntax to bring in a package as an extension of another package

To expand map projections in D3, it is recommended to import the necessary packages like so: const d3 = require("d3") require("d3-geo-projection")(d3) This allows you to access methods such as d3-geo-projection's geoAiry method fr ...

The redirection from HTTP or www to HTTPS is not functioning as expected

Redirecting all links to my website to the https:// domain is supposed to work flawlessly, but there are certain ways it doesn't quite function as expected. https://www.example.com --- works example.com --- works www.example.com --- encounters issu ...

Customizing the JavaScript Calendar in Qualtrics

I came across a JavaScript code snippet that allows you to embed a calendar into a Qualtrics question. Specify a date for the survey: <link href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css" rel="stylesheet" type="text/css" /> <script sr ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Dealing with problems related to types in React and TypeScript createContext

Struggling to pass the todos (initial state) and addNewTodo (methods) using React Context hook and typescript. Despite trying multiple solutions, errors persist. Partial generics do not cause issues in the context component, but I encounter the error Cann ...

Is MapView in React Native restricted to explicit markers only?

I'm facing a challenging problem while working on my app's mapview. I have been struggling to find a solution for dynamically repopulating the mapview. Initially, I attempted the following approach: render() { const dynamicMarker = (lat, long, ...

Knex is requesting the installation of sqlite3, but I am actually utilizing a MySQL database

While attempting to execute a query on my local MySQL database using knex, I encountered an issue where it prompted me to install the SQLite3 driver, even though my database is MySQL. To troubleshoot, I installed the SQLite3 driver to see if it would reso ...

Activate the Select List to Appear Only When a Search is Conducted

Currently, I have implemented the react-select API in order to provide language options for selection. <Select isMulti name="langs" options={langOptions} defaultValue={{ value: "English", label: "English", nativeNam ...

Is there a way to extract the content from a dynamic textbox using a dynamic button in HTML and AJAX?

My current task involves fetching data from a database and updating the records individually. I have created a table with a text input field and a button that will be generated dynamically for each record. The text input field is populated with the previou ...

JavaScript obtain scroll position of a child element

I have a setup that looks something like the following: <div> <div id="scrollID" style="height:100px;"> content here </div> </div> <script> document.getElementById("myDIV").addEventListener("touchstart", m ...

Step-by-step guide on opening a modal popup, retrieving information from a database, presenting it in the popup, and saving any modifications as per the user's instruction

In my current project, I am utilizing Flask along with psycopg2. One of the requirements is to create a page titled "List of Payments" which displays a table containing payment information. The manager has requested the ability to view card details and edi ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

Obtaining numerous data points in a multi-select element within HTML

Struggling with determining the values of multiple <select> tags in an HTML file simultaneously? function knowAllValues(){ var color_element = document.getElementById("color"); var size_element = document.getElementById("size"); ...

Guide for preventing hours before the scheduled date and time with v-calendar

I am utilizing v-calendar to display the start date and time as well as end date and time in dateTime mode. My goal is to prevent the end date and time from being set before the start date and time. In order to achieve this, I have implemented the :min-dat ...

Explore a nested array of objects to identify and retrieve the complete pathway for every matching item

Looking for a solution to search through a deeply nested array of objects and retrieve the paths of all matching objects? While I have made progress on the problem, the current code only returns the path of the first matched object. Take a look at the inpu ...

Organize a list using custom span values with JavaScript

<ul id="CoreWebsiteTopHeader_6_list"><li><a class="navigation" href="/seller"><span class="editableLinks" data-id="32638" data-sort="110">Seller</span></a></li><li><a class="navigation" href="/about">&l ...

Using Node and Mongoose to link documents that rely on each other for reference

Is there a way to add a document after another document has been successfully inserted using node and mongoose? For example, I initiate the creation of a document with mongoose, and once it is successfully added, I want to trigger the insertion of another ...

Using the TypeScript compiler API to determine the location in the generated code of a particular AST node

I am aiming to retrieve the specific TypeScript AST node's location (start and end) in the emitted JavaScript file. Consider this code snippet: const program = ts.createProgram(tsconfig.fileNames, tsconfig.options); const aNode = program.getSourceFi ...

How can you ensure an element's height matches its width within an Ionic framework?

I am currently creating an application using the Ionic framework, and I am looking to set a square image as the background. The challenge is to ensure that the image scales appropriately for different screen resolutions; ideally, it should occupy the full ...

Can fog be applied from a fixed location within a three.js scene without being tied to the camera's position?

Is it feasible to render fog in such a way that an avatar on a terrain remains clear while the surrounding area gradually fades into the mist, especially when the camera is positioned overhead at a distance? ...