Increase the date by days in gradual increments over multiple years

I am trying to figure out how to increment a date by adding days and then expanding that date over a specific time period. I have encountered an issue with getting the date to increment correctly without using a plugin. Any suggestions? One key problem is when the dates extend into a new year, it always defaults to the current year due to how I initialized the date. If my explanation is unclear, please feel free to ask questions for clarification.

var last, packEndDate, packStartDate;

while (i < frequencyValue) {
  packStartDate = new Date();
  packEndDate = new Date();
  debugger;
  if (isWeek) {
    packStartDate.setDate(startDate.getDate() + (7 * i));
    packEndDate.setDate(packStartDate.getDate() + 7);
  } else {
    packStartDate.setDate(startDate.getDate() + (30 * i));
    packEndDate.setDate(packStartDate.getDate() + 30);
  }
  last = frequencyValue - 1;
  if (i === last) {
    packEndDate = endDate;
  }
}
i++;
}

Answer №1

By manipulating the number of milliseconds since January 1, 1970, 00:00:00 UTC, you can easily create new Date objects that represent moments in the future. This method allows you to add a fixed amount of time to the current date without needing to worry about specific calendar details like the year or day of the week.

If you're looking to increment a specific date by a set number of days within a loop, you can use the following code snippet:

var numberOfDaysToIncrement = 7;
var offset = numberOfDaysToIncrement * 24 * 60 * 60 * 1000;

var currentDate = new Date();
var incrementedDate = new Date(currentDate.getTime() + offset);

Answer №3

Adjusted my code to appear like this:


packagesToAdd = []
packStartDate = new Date()
packEndDate = new Date()

while i < frequencyValue
    if isWeek
        toIncrementWeekly = 7 * i
        offset = toIncrementWeekly * 24 * 60 * 60 * 1000
        packStartDate = new Date(startDate.getTime() + offset)
        packEndDate.setDate(packStartDate.getDate() + 7)
    else
        toIncrementMonthly = 30 * i
        offset = toIncrementMonthly* 24 * 60 * 60 * 1000
        packStartDate = new Date(startDate.getTime() + offset)
        packEndDate.setDate(packStartDate.getDate() + 30)

    last = frequencyValue - 1
    if i == last
        packEndDate = endDate

    number = ('0' + i).slice(-2)
    i++

Operates flawlessly. Appreciations to dmlittle.

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

Node.js socket.io: How to Handle Multiple Returned Values from a Single Event

I've been working on a simple chat app using Node, Express (^4.15.3), and socket.io (^2.0.3). However, every time I add a new message, I notice that I get an additional response each time. For instance, when I send the message "Hello" for the first t ...

Mastering the art of implementing async/await properly within token validation scenarios

I am currently working on setting up an Express.js backend for a website that authenticates users using Google Sign-in. My goal is to develop a RESTful API call that: Accepts an ID token. Authenticates the token using Google's OAuth2 Library. Veri ...

Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database. The challenge arises when dealing with data that contains single quotes within th ...

Use jQuery to transfer groups of table rows to a newly relocated table data cell

First of all, I appreciate you taking the time to go through this explanation. My current challenge involves using jQuery to move sets of TRs to new positions in a table. While I can easily move the headers, I am facing difficulty with moving the actual da ...

Creating a JSON String Using Two Separate Dictionaries?

Currently, I am utilizing json.net (newtonsoft) and facing an issue with building a json request involving 2 different dictionaries. I'm unsure how to merge them together. Dictionary<string, HttpStatusCode> code = new Dictionary<string, Htt ...

Dynamic Node.js server executing a separate JavaScript file in real-time

I need to execute my scrapers at a specific time. For example: Let's say I want the scrapers to run at 09.00.00 I have multiple scrapers to run. I recently discovered a method to do this, but I'm concerned it may not be reliable. setInterval( ...

Transferring user authorization from child to parent component in ReactJS

I'm currently facing a challenge where I need to transfer data from a function to a parent component and then to its child component. The FetchUserPermissions function queries a mock database to retrieve a list of user permissions. The goal is to pas ...

Obtaining the MapOptions object from a map using Google Maps API version 3

Previously in Google Maps api v2, you were able to retrieve map parameters like the type and zoom directly from the map object. However, in version 3, the setOptions method is used to configure parameters, but there is no equivalent method like getOption ...

What is the unit that you can deduct from a JavaScript / MongoDB Date object?

In relation to the query found at , I am seeking guidance on deducting N days from a Date object. Given that MongoDB utilizes JavaScript data types, my inquiry is this: When subtracting X from Date(), does X represent seconds? Minutes? Or microseconds? ...

Discovering the parent route details of the current route from within a component

I am facing an issue where I need to identify the parent route /products while working within the scope of the FeaturedProducts.vue component. The current route path for this component is set as /product-list/featured const routes = [ { path: "/ ...

Guide to successfully merging Mysql data with PHP into the ParamQuery Grid using Javascript

Could you please assist in converting the JSON output from MySQL into the desired format shown below? JSON [ {"storenm": "S1", "FA_SOH": "20964", "FA_CY_QTY": "15", "FA_CT_QTY": "44497"}, {"storenm": "S2", "FA_SOH": "1096", "FA_CY_QTY": "2", "FA_ ...

Is there a way to customize the CSS ul menu specifically for the JavaScript autocomplete feature?

I have created a search page with autocomplete for the first textbox, but I noticed that the ul/li CSS classes used for styling the main menu are impacting the JavaScript list. How can I override the menu styling to display a regular list format? Being a ...

nunit-console is unable to execute tests that are parameterized using the TestCase attribute

I'm attempting to execute Nunit tests with parameters using the TestCase attribute. Here is an example of what I'm trying to do: [TestFixture] public class MyClass { [Test] [TestCase("option1")] [TestCase("option2" ...

Using the back button in the browser can undo any CSS modifications made by JavaScript

I'm currently working on a form that changes the displayed select lists based on the selection of a previous list. HTML <select name="college" id="college" onchange="show_majors()"> <!-- <option value="-">-</option& ...

Retrieve all CSS properties associated with a specific DOM element, similar to the functionality provided by Firebug

Is there a method to retrieve all the CSS styles specified for a specific DOM element? Do I need to iterate through all the CSS style names? Could there be a more sophisticated approach? How exactly does Firebug achieve this task? Appreciate any insights ...

Building a fresh User profile with Firebase and Vue

Hey there! I'm currently in the process of developing a user system using Vue and Firebase. I've successfully included the necessary Firebase script in my project along with some code. However, I'm running into an issue where clicking on the ...

Tips for linking rows across different tables

I'm facing a scenario where I have two tables and the challenge is to enable the user to establish a connection between rows from one table with rows from another. For example: When the user eventually clicks on the submit button, I require the infor ...

Emphasizing specific lines using an array

There is a block of text containing multiple lines, each wrapped within a span with an incremented value at the end (like line-1, line-2, line-3, and so on) to distinguish between them. <div id="textbody"> <span id="line-1">what is love< ...

How can I dynamically change the orderBy parameter based on conditions in an Angular application?

I need to dynamically change the orderBy parameter in a table row based on the result of a method. Here is an example of my current tr setup - <tr class="pl" ng-repeat="thing in things | orderBy:'oldId':reverse" ng-class="{'row-error&apo ...

Searching does not reset when you click on a JavaScript onclick event

I have an interesting situation - I've set up a JavaScript onclick event that will parse JSON data from my MySQL database and display it when someone clicks on a seat. var jsonData = <?php echo json_encode($array); ?>; function displayInfoFo ...