JavaScript does not always display the correct results for past day dates

I am trying to retrieve a date in the "YYYY-mm-dd" format from some days ago using the following function:

function getDifDate(d, numd) {
 d = stringToDate(d);
 d.setDate(d.getDate() - numd);
 return d;
}

Subsequently in another section of the program, I have written:

var tod = new Date();
switch(selPer.value) {
            case 1:         
                x= getDifDate(tod, 2);
                break;
            case 2:
                x= getDifDate(tod, 15);
                break;
            default:
                //default code block
        }
        console.log("Data1: "+ x);

The issue I am experiencing is that regardless of when I run the script, the value for x always returns as "25". What could be causing this inconsistency?

Any insights would be greatly appreciated.

Answer №1

This code snippet is designed to function smoothly even without the dependency on DateJS

function calculateDateDifference(date, numDays) {
 date.setDate(date.getDate() - numDays);
 return date;
}

var result;
var today = new Date();
switch(1) {
            case 1:         
                result = calculateDateDifference(today, 2);
                break;
            case 2:
                result = calculateDateDifference(today, 15);
                break;
            default:
                //default implementation
        }

console.log("Updated Date: ", result);

To see this code in action, visit: http://plnkr.co/edit/gLwBIfAp7zFLEaV1KJ1O?p=preview

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

Transmitting data using JavaScript to Spring server

I am facing a challenge of uploading an image to a server using Spring. The code snippet I am using to get the file is as follows: var file = $("#form-field-photo").get(0).files[0]; I have attempted several methods to post it, but so far, all my attempts ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

Error thrown by Jest: TypeError - req.headers.get function is not defined

I have a function that is used to find the header in the request object: export async function authorizeAccess(req: Request): Promise<Response | {}> { const access = req.headers.get('Access') if(!access) return Response.json('N ...

What is the best way to include parameters when calling $resource.query in AngularJS?

Currently, the url localhost/view/titles is set up to use the specific route, controller, and service described below. When accessed, the server will return a list of all title objects. How can the service be expanded to accommodate additional query para ...

Despite my efforts, I am struggling to refresh the view after retrieving data from an AJAX call in AngularJS

I've been searching for a solution to this problem for quite some time now, but nothing seems to work for me. Recently, I started delving into Angular and managed to create a basic page with an ng-repeat function that iterates through an object. My ...

What methods can be utilized to conceal an if statement in code?

In my application, I am facing an issue with an external JavaScript file that contains multiple if statements. The problem arises when one of the if statements is still being executed even if the corresponding form is hidden. The flow of my application is ...

Ajax updates previous text to new text upon successfully completing the task

I have a question regarding changing text using AJAX after success. I have written this AJAX code which is functioning properly. However, I aim to replace the old text with new text in the .chnged div. For instance: <input type="text" name="text" va ...

What is the solution for the error "Firebase limitToLast is undefined"?

How can I restrict the number of items returned when watching the 'value' in my Firebase database? I keep getting an undefined error when using orderByChild on my Firebase reference. $scope.watchRef = new Firebase(ActiveFirebase.getBaseURL() ...

Firefox fails to trigger HTML drag event

After successfully implementing draggable header columns on a table using Chrome as my browser, I encountered an issue when testing it in Firefox (version 17.0.1). It seems that the drag event does not fire in Firefox, although the dragstart event does. ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...

Modifying an object using setState in React (solidity event filter)

Is it possible to update an object's properties with setState in React? For example: this.state = { audit: { name: "1", age: 1 }, } I can log the event to the console using:- myContract.once('MyEvent', { filter: {myIndexedParam: ...

What steps should be followed to properly validate an unsubmitted form in Angular?

To ensure that the user submits the form before navigating to another page, I want to implement a feature where an error dialog pops up if the user types in the form but hasn't submitted it yet and tries to click a link to go to a different page. How ...

Using the append() method in d3 with a function argument adds new

This is functional code: // A d3.select("body").selectAll(".testDiv") .data(["div1", "div2", "div3"]) .enter().append("div") .classed("testDiv", true) .text(function(d) { return d; }); The next snippet is essentially the same, except that ins ...

Is XML parsing used by AJAX?

Is an XML parser used by AJAX? If so, where is it used? I believe that the client-side JavaScript engine utilizes the DOM parser to extract necessary information from the XML document received from the server. Could it be possible that AJAX doesn't us ...

Why is the inner span element not being referenced in jQuery?

I've come across a specific HTML structure: enter code here <ul> <li><span>aaa</span> <div> <ul> <li><span>bbb</span> </li> </ul> ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Looking for advice on successfully implementing createMultiMaterialObject in THREE.js version r62?

I am having trouble getting createMultiMaterialObject to work as expected. My goal is to have a wireframe material displayed on top of a solid material. However, the multimaterial function only seems to display the first material in the array. Here is the ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Seamless side-to-side navigation

Currently, I am working on a website that has horizontal overflow instead of the common vertical scroll. While everything seems to be functioning properly, I need to enhance the user experience by adjusting the amount scrolled to move larger sections of th ...

Generating objects dynamically using an array of paths in dot notation

Is it possible to dynamically generate an object with an array of strings in dot notation? The idea is to construct a JSON object from a CSV file, filter the properties, and create a new JSON object. Let's say we want to pass something like this... ...