How to calculate a date x days before a given date using javascript

In my Angular application, I am dealing with a date value that is stored in local storage.

My current code snippet retrieves the date like this:

$scope.selectedDate = localStorage.getItem('selDate');

The returned date from this code is '11-4-2015'.

However, what I actually need is to get this date minus 85 days.

I attempted the following:

var hearingOffset = 85;
var selectedDate = new Date(localStorage.getItem('selDate').replace(/-/g, '/') - hearingOffset);

Unfortunately, this resulted in an "Invalid Date" error.

How can I adjust the code to obtain the correct date?

Answer №1

Timekeeper is a great tool for this task.

Timekeeper(date).decrement(85, 'days').getDate()

Answer №2

Just sharing a helpful tip with you

var d = new Date(); // current date
var x = 85; // going back 85 days
d.setDate(d.getDate() - x);

After obtaining the date, you can easily convert it to your desired format

UPDATE

When subtracting dates, the result is in milliseconds so we need to convert it back to a date object.

var d = new Date('11-4-2015');
var x = 85; // going back 85 days
var y=d.setDate(d.getDate() - x);
var date = new Date(y);
document.getElementById('dateHolder').innerHTML=date;

Check out the updated Fiddle here

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

Error: Trying to access the 'commit' property of an undefined variable in Angular

I am currently working on a project that involves Angular and Spring Boot integration. The project retrieves parameters from the Spring Boot back-end through a DTO, and I display this information on the front-end screen. However, upon showing the dialog co ...

Having trouble with nested requests and appending using Jquery or JavaScript?

Greetings everyone, I want to apologize in advance for any spelling errors or mistakes in my message. I struggle with dyslexia and other learning difficulties, so please bear with me. I am using this time during lockdown to learn something new. This is my ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...

Tips for choosing a block using Puppeteer

Trying to retrieve the height of a series of blocks using Puppeteer, I encountered an issue where I couldn't select my block in page.evaluate() due to an error. The code snippet in question is as follows: (async () => { const browser = aw ...

Establishing a default selection for a react dropdown menu filled with data retrieved from an API request

class Select extends React.PureComponent { constructor(props) { super(props) this.state = { value: this.props.initialValue } this.handleChange = this.handleChange.bind(this) } handleChange(e) { e.persist() ...

What is the best way to save data in order to effectively showcase a collection of images that together form a single entity in a game

Apologies for the unclear title, I struggled to find the right words. Recently, I delved into the world of 2D game development and was amazed by the capabilities of HTML5's Canvas element. Currently, I am working on my first basic project to grasp th ...

Injecting a variable into JavaScript using CodeIgniter

I've encountered an issue where I am unable to pass a variable from Codeigniter's view to the controller and then to the model for executing the necessary query to retrieve data from the database. Below is a snippet from my Controller: public f ...

The components for my children are not being displayed within the Drawer component in Material UI and React

Why are the Material UI components and other project components not displayed when I use my DrawerForm component? List of dependencies: react: 18.2.0 react-dom: 18.2.0 @amcharts/amcharts5: 5.3.6 @mui/icons-material: 5.11.11 @mui/material: 5.11.12 Code s ...

Confirming an authorization?

I have been working on this code and it is almost perfect, but I am struggling to understand why it needs to validate the 0 or 10 in order to work correctly. The issue I am facing is with a validation where the button should be deactivated when the counte ...

The load event in React's iframe is failing to fire after the src attribute is modified using state

In the process of creating a registration form for a React application, we encountered the need to incorporate an HTML legal agreement as an iframe. This legal document is available in various languages, one of which can be selected using a drop-down menu; ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

MongoSearch: A Geo-Targeted Search Engine tailored to your needs

For my new app project, I am using MongoDB, Express, JS, and Node to create a platform similar to Yelp. After some research, I discovered how to search for multiple fields within a campus schema (including campuses, restaurants, barbershops, and names). No ...

Switch out a character with its corresponding position in the alphabet

Starting out, this task seemed simple to me. However, every time I attempt to run the code on codewars, I keep getting an empty array. I'm reaching out in hopes that you can help me pinpoint the issue. function alphabetPosition(text) { text.split ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...

Challenges arising from the rendering of main.js in Vue.js

Recently, I started working with Vue and am now faced with the task of maintaining a project. Main.js contains the routing structure: Main.js import Vue from 'vue' const app = new Vue({ el: '#app', data: { message: & ...

Altering the way in which URL parameters are attached to links depending on the destination

Our company utilizes Unbounce to create PPC landing pages on a subdomain, which then direct users back to our main website. We have implemented code that appends the AdWords gclid variable to outgoing links: $(document).ready(function() {var params = win ...

The hamburger menu on the responsive navbar fails to open when clicked on

Having an issue with my navbar in mobile and responsive environments. The hamburger menu shows up, but when clicked on, the links are not displayed. Below is the code that I am using, all the necessary links are included but the menu is not functioning pro ...

The Vuetify data-table header array is having trouble accepting empty child associations

My Vuetify data-table relies on a localAuthority prop from a rails backend. Everything runs smoothly until an empty child association (nested attribute) is passed, specifically 'county': <script> import axios from "axios"; exp ...

What is the best way to reset form after submission in Next.js?

I have a contact form and I want all the form values to be cleared after submitting the form. I've tried the following code, but the values of the form remain unchanged after submission. What could be causing this issue and how can it be resolved? ...

What is the best way to detect and handle the destroy event in Kendo UI grids when a click event

How can I trigger a function when the delete button in a grid is clicked using JavaScript? ...