JavaScript: Increasing the date by a certain number of days

I've been researching various topics and so far, I haven't come across one that addresses my specific issue.

Here's the task at hand:
1) Extract a bill date in the mm/dd/yy format, which is often not today's date.
2) Add a dynamic number of days to this date using the terms saved in the dueTime array below. For now, I've limited it to 30 days.
3) Calculate the due date of the bill based on the original bill date and the payment terms, then return it in the mm/dd/yy format.

I've attempted a solution, where the input into new Date appears correct, but the output never matches my expectations.

Thank you for any assistance you can provide.

<html>
<head>
<script>
function calculateDueTime(){
    var billDate = document.getElementById('billDateId').value;
    var key = document.getElementById('termsId').value;
    var dueTime = new Array();
    dueTime[1] = 30;
    var billDateSplit = billDate.split('/');
    var newDate = new Date( parseInt( billDateSplit[2] ) + '/' + parseInt( billDateSplit[0] ) + '/' + ( parseInt( billDateSplit[1] ) + parseInt( dueTime[key] ) ) ); 
    document.getElementById('dueDateId').value = newDate.toString();
}
</script>
</head>
<body>

<input name="billDate" id="billDateId" value="5/1/11" /> 
Enter date in mm/dd/yy or m/d/yy format
<select name="terms" id="termsId" onchange="calculateDueTime()">
   <option value="1">Net 30</option>
</select>
<input name="dueDate" id="dueDateId" />

</body>
</html>

Answer №1

To calculate a new date, simply add the desired number of days to the current date:

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 31);

console.log(currentDate);

Answer №2

If you're tired of dealing with JavaScript date headaches, I recommend checking out Datejs (). This library has been a lifesaver for me when working with dates.

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

Guidelines on Sharing Redux Store with Client during Routing in Redux

I'm currently learning Next.js and facing an issue with maintaining the dispatched state on a newly built page after routing. Can anyone provide guidance on how to retain the state? Specifically, I have a sidebar where I want to preserve the state of ...

Mastering the art of transforming JSON data for crafting an exquisite D3 area chart

I often find myself struggling with data manipulation before using D3 for existing models. My current challenge is figuring out the most efficient way to manipulate data in order to create a basic D3 area chart with a time-based x-axis. Initially, I have a ...

Sending a prop to a handler causes issues with navigation paths

I'm facing an issue with my handler and button component setup. Here's my handler: const addToCartHandler = (id) => { navigate(`/cart/${brand}/${id}?qty=${qty}`)}; And here's the button component using the handler: <Button onClick={a ...

Set the value of a variable to the result of a JavaScript function

I recently wrote a function that retrieves JSON data from a specified URL. Here's what the function looks like: function getJSON(url) { request.get({ url: url, json: true, headers: { 'User-Agent': 'request&a ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

Instructions for receiving user input and displaying it on the screen, as well as allowing others with access to the URL to view the shared input provided by the original user

<h1>Lalan</h1> <input type="text" name="text" id="text" maxlength="12"> <label for="text"> Please enter your name here</label> <br><input type="submit" value ...

Transferring information to the server with JSON in the Codeigniter framework

I have a JavaScript array (unitdata_set) that I need to send to the server for database processing using Codeigniter. JavaScript Array (unitdata_set):- [{"unit_id":"13","unit_title":"Testsdsdf","unit_max_occupancy":"3","unit_no":"1","unit_no_adults":"1", ...

Access a document from a collaborative directory directly in a web browser

When I paste the shared path for a PDF file into the address bar, it opens perfectly in all browsers. The code below works fine in IE 8 but not in Chrome and Firefox. Code: function openPDF(file) { window.open(file, '_blank'); } function link ...

Steps for creating checkboxes for individual table rows in HTML using embedded PHP and updating their values in a PostgreSQL database:1. Begin by iterating through each

I have already retrieved the data from the database. It is displayed on the HTML table, but it is currently in non-editable mode. I need to ensure that the data shown is accurate and update its Boolean value in the database. Otherwise, incorrect records sh ...

Contrasting deleting a node_module folder with running npm uninstall to remove a specific package

Do manual deletion of a package directly from the node_modules folder and running npm uninstall really make any difference, considering that npm just deletes the package anyway? ...

Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class? class Car { wheels: number; model: string; } const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'}; const goodCar = filterUnwant ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

What causes the unexpected behavior of __filename and __dirname after being minified by webpack?

Could someone offer some insight into a strange issue I've encountered? In my project, the structure is as follows: index.js src/ static/ favicon.ico styles.css server.js routes.js app.jsx //[...] dist/ /sta ...

Is it possible to exclude certain static files from being served in express.static?

const express = require('express'); const app = express(); app.use('/app', express.static(path.resolve(__dirname, './app'), { maxage: '600s' })) app.listen(9292, function(err){ if (err) console.log(err); ...

width of the cells within the grid table

What is the best way to ensure the width alignment of cells in both the header and main section? I have highlighted the correct option in the image with green checkmarks. Check out the image here. Here is my example and solution: View the code on CodePen. ...

Exploring the connection between two MongoDB collections

I currently have two collections in my MongoDB database: Category and Book Here is the category.js code: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categoryModel = new Schema({ catName: String, menuKey: String }); module.ex ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

Removing classes from multiple elements on hover and click in Vue 2

Can Vue be used to remove a class from an element? I am looking to remove the class when hovering over the element, and then add it back once the mouse is no longer on the text. Additionally, I want the class to be removed when the element is clicked. He ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...