JavaScript's getDate() function is failing to properly adjust the date when performing addition and subtraction operations

I have been facing an issue with a JavaScript function that is supposed to adjust the date when a button is clicked. The function is intended to utilize the getDate() function to subtract 7 days from the current date value displayed in the textbox. However, despite my attempts to troubleshoot and correct the problem, I have not been successful in resolving it. The main issue is that every time I click the button, instead of deducting another seven days from the date, it jumps to an entirely different date. For instance, if the date in the textbox is 05/01/2014, clicking the button takes it to 29/12/2014, and clicking it again shifts it to 28/11/2015, rather than the expected 22/12/2014.

Below is the excerpt of my JavaScript code:

   var fromDateIn = new Date(formatDate(document.getElementById('<%= txtFromDate.ClientID%>').value));
      var newdate = new Date(fromDateIn);
      newdate.setDate(newdate.getDate() - 7);
      var nd = new Date(newdate);

      document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(nd);

     function formatDate(inputDate) {

      var d = new Date(inputDate || Date.now()),
    month = '' + (d.getMonth() + 1),
    day = '' + d.getDate(),
    year = d.getFullYear();

      if (month.length < 2) month = '0' + month;
      if (day.length < 2) day = '0' + day;

      return [day, month, year].join('/');

  }

I am seeking assistance in identifying the correct method to consistently subtract 7 days from the current date value in the textbox. Any insights are greatly appreciated.

Thank you

Answer №1

The root of your problem lies in the fact that you are utilizing your formatted date to create the new fromDateIn.

Make sure to initialize the value upon loading, and incorporate the newdate variable for the calculation. Trigger the changeDate() function upon clicking the button.

var fromDateIn = new Date(formatDate(document.getElementById('<%=txtFromDate.ClientID%>').value));
var newdate = new Date(fromDateIn);

function changeDate() 
{
   newdate.setDate(newdate.getDate() - 7);
   document.getElementById('<%= txtFromDate.ClientID%>').value = formatDate(newdate);
}

function formatDate(inputDate) 
{        
   var d = new Date(inputDate || Date.now()),
   month = '' + (d.getMonth() + 1),
   day = '' + d.getDate(),
   year = d.getFullYear();

   if (month.length < 2) month = '0' + month;
   if (day.length < 2) day = '0' + day;        
   return [day, month, year].join('/');        
}

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

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

Utilizing ES6, accessing the first element of an array of objects

How can I access the values of the first or a specific object in an array based on an index using ES6? arrayOne =[ { child: [ {e1: 'ABCD', e2: 'BCDF'}, {e1: '1234', e2: '5689'}, {e1: 'QAZ ...

Error: The use of import statement is not allowed outside a module in JavaScript due to a Syntax

I'm just beginning my journey with React, starting from scratch without setting up all the necessary dependencies. Initially, I used CDNs in my html file but now I want to learn how to import React and ReactDOM into my local setup and also link CSS fi ...

Conquering disparities in standards mode with Javascript

Having an issue with this code snippet: function scrollLeft() { document.body.scrollLeft -= scrollSpeed; } While it works fine in Chrome and Safari, it doesn't seem to work in IE and Firefox. Found out that the problem lies in the fact that Fire ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

The issue of Next.js redux useSelector causing HTML inconsistency

Currently, I am utilizing Next.js for the development of a React application. In order to manage the state, I have integrated redux along with redux-toolkit. A peculiar error has surfaced in the console with the message: Warning: Did not expect server H ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

A single parallax transition designed exclusively for you

I am looking to add a unique parallax transition to my website, specifically one that features a nice scroll followed by a subtle bounce effect. For example, I want to incorporate an arrow that, when clicked, smoothly scrolls the user to the bottom of th ...

What is the best way to gather the contents of several textboxes and save them in a single variable?

I've been working on a page that should calculate total hours worked, but unfortunately, I'm facing issues with the output. I've tried using both querySelectorAll and getElementsByTagName by switching the class tag to the name in the textbox ...

Why are my functions still being called asynchronously? I must be missing something

My task involves downloading 5 files exported from our school's database and running a query based on the first export. There will be queries for the other four files, and since there are three schools, my functions need to be scalable. I have two fu ...

Tips on retrieving a <list> from an MVC controller and passing it to the view with jQuery and AJAX

How can I retrieve a list from an MVC controller to a view using jQuery AJAX without getting the error message [object Object]? Here is my AJAX code: $.ajax({ type: 'POST', contentType: 'application/json; ch ...

Is it possible to bypass configuring Azure KeyVault in a development environment?

While working with Azure KeyVault, I encountered an issue where the setup in Program.cs file only works when the Azure account in Visual Studio has access. If the account loses access, an error is thrown. Is there a way to skip setting up the key vault fo ...

Transferring data between two HTML files through the POST method

Is there a way to pass two values (parameters) from one HTML page to another without displaying them in the URL, similar to using the POST method? How can I retrieve these values on the second HTML page using JavaScript, AJAX, or jQuery? For example: cli ...

React Foundation accordion not functioning properly

Utilizing Foundation accordion within my React component has presented a challenge. The code functions properly when rendering static HTML, but when attempting to render it dynamically through a loop, the accordions lose their clickability. React code fo ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

In Visual Studio, the .js.map files and .js files seem to be mysteriously hidden, leaving only the TypeScript .ts files visible

In the past, I utilized Visual Studio Code for Angular 2 development and had the ability to hide .js and .js.map files from the IDE. Now, I am working on a project using VS 2017 Professional with Typescript, Jasmine, Karma, and Angular 4. Task Runner, etc. ...

Is it possible to import npm modules conditionally?

Here is the structure of my project: - workspace - customPackage - customIndex.js - myProject - index.js - myProject2 - index.js During development, I need to import the package from my local workspace like this: //index.js import some ...

What do you believe to be superior: Vue UI design?

Scenario: Application managing multiple user roles. A view with extensive conditional rendering in the template. a) Is it preferable to have numerous conditional statements in a single view's template? b) Should separate views be created for each ro ...

Multiple curl requests being sent to an IIS server with a single authorization

Situation: Our company utilizes an IIS Server and MVC website with multiple web API controllers that require Active Directory account authorization. Additionally, we have several Linux machines in our environment. I typically use curl for Windows in my e ...