Adjusting the date backward by one month results in a difference of 30 days, transitioning from July 31st to August

I'm feeling a bit overwhelmed by the code below.

var forDt = new Date("2017-07-31"+ "T09:00:00.000");
    var workDt = new Date();
    workDt.setDate(forDt.getDate() - 1);
    date_prev = workDt.toISOString().slice(0, 10);

Today is August 1st. I clicked a Prev button twice and datePrev changed from July 31 to August 30.

I need some assistance in figuring out what went wrong in my code. It seems like setDate() is setting 31-1=30 without updating the month. Can someone help me fix this issue?

Thanks in advance, everyone! =)

Answer №1

When you create a new Date(), the variable workDt will now represent the current date of the system.

var forDt = new Date("2017-07-31" + "T09:00:00.000");
var workDt = new Date(forDt.getTime());
workDt.setDate(forDt.getDate() - 1);
date_prev = workDt.toISOString().slice(0, 10);

console.log(date_prev);

workDt.setDate(workDt.getDate() - 1);
date_prev = workDt.toISOString().slice(0, 10);

console.log(date_prev);

By using new Date(forDt.getTime()) to set workDt, you are creating a duplicate of the date you want to adjust. By modifying the day of the month, you will arrive at the correct result.

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

Find the position of an HTML5 canvas element within a webpage

I am currently facing an issue with a canvas within another canvas. <canvas id ='canvas2' height="718" width="1316"></canvas> The CSS for this canvas is as follows: #canvas2{ position:absolute; width :95%; height:90%; top:5%; lef ...

How can I subtract a value from an array using node-js?

If we consider a simple scenario where an array totalSpots = [95] contains only one value, and a new booking is made, the goal is to automatically assign one parking spot to the user who booked it. This will involve reducing the value in the array by 1 or ...

Creating an autocomplete feature with just one input field to display information for two to three additional input fields

I'm working on implementing an autocomplete feature similar to this example: . Feel free to test it out with the code snippets provided: 1000, 1001. I've successfully implemented the autocomplete functionality where typing in Pa suggests Paris. ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Exporting an HTML table to Excel with JavaScript runs into issues when it encounters the '#' character

Looking for a JavaScript solution to export HTML tables to Excel. I attempted a script that exports tables, but it stops when encountering special characters like '#'. Can someone assist me with this issue? Thank you in advance. <script src= ...

Setting up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

The code functions correctly on JSfiddle, however it is not executing properly on my website

When I tried to implement the code from this jsfiddle link: http://jsfiddle.net/mppcb/1/ on my website (), it didn't work as expected: Here is the HTML code snippet: <form id="myform" novalidate="novalidate"> <input type="text" name="fi ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Generate a JSON file using Node.js

I've been honing my skills with Node.js and express by working on a project involving a JavaScript object that generates a dropdown list. The process has been smooth so far. Recently, I integrated mongoose to create a model and saved it. Now, in my co ...

Tips on adding custom fonts for text geometry in three.js

Currently, I am delving into the realm of three.js to create text geometry, although my expertise in JavaScript is fairly limited. Initially, I attempted to utilize my custom JSON font, which resulted in the same error encountered when using fonts from th ...

What steps can be taken to ensure web resources such as scripts, images, etc are loaded from the correct location when implementing CORS support in a web application

In my local IIS, I have two asp.net mvc applications running on different ports. One is "App1" on port 1066 and the other is "App2" on port 1067. My requirement is for App2 to post data to an endpoint in App1 for validation. If the data is valid, App1 sho ...

Node.js client encounters ENOBUFS error due to excessive number of HTTP requests

Currently, I have the following setup: An end-to-end requests system where a node.js client communicates with a node.js server. However, the issue arises when the client fails with an ENOBUFS error in less than a minute. client: (function(){ var lo ...

AngularJS utilizes $location but includes a refresh option

Back when I used ui-router, I recall there was a command like $state.go('/',{reload:true}). However, with normal ngRoute, how can I navigate to a page and also refresh it? I haven't found any option in $location. ...

Develop a specialized WordPress widget featuring several unique text areas for enhanced customization

class ad_widget extends WP_Widget { function __construct() { $widget_ops = array( 'classname' => 'ad-widget-container', 'description' => __( ' Ad WIDGET' ) ); parent::__construct( 'ad-widget', ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Troubles with DropDownList onChange event when selectedIndex is at 0

Hey there, I have a question that's been puzzling me. I have three security question dropdown menus on my ASPX page with JavaScript that removes and repopulates questions based on user selection. Everything works great when editing an existing profile ...

Discover the secrets of accessing two distinct objects returned by a single REST URL with Backbone

I am working with a REST URL that looks like this: /users/<user_id>/entities This URL returns data containing 2 objects as follows: { "players": { "test_player2": { "_id": "test_player2", "user": "f07590 ...