Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below:

  addDays(date: Date, days: number): Date {
    console.log('adding ' + days + ' days');
    console.log(date);
    date.setDate(date.getDate() + days);
    console.log(date);
    return date;
  }

Let's see some examples of its output:

Everything seems fine at first:

adding 7 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Tue Aug 09 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))

But then it starts to malfunction:

adding 14 days
error-chart.component.ts:118 Tue Aug 02 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Mar 02 2017 00:00:00 GMT+0100 (Vest-Europa (normaltid))

Suddenly, it jumps ahead by two years:

adding 14 days
error-chart.component.ts:118 Thu Jul 07 2016 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))

And then, it continues to exhibit unexpected behavior, now jumping four years:

adding 14 days
error-chart.component.ts:118 Thu Jun 14 2018 00:00:00 GMT+0200 (Vest-Europa (sommertid))
error-chart.component.ts:120 Thu Apr 14 2022 00:00:00 GMT+0200 (Vest-Europa (sommertid))

Answer №1

You seem to be facing an issue with data types. In the scenario where days is set to 14, the correct output should be August 16th. However, if days is assigned as "14", then you will get March 2nd as the result.

Here is a possible solution:

  addDays(date: Date, days: number): Date {
    console.log('adding ' + days + ' days');
    console.log(date);
    date.setDate(date.getDate() + parseInt(days));
    console.log(date);
    return date;
  }

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

Exploring the functionality of Material-UI's TextField component through role-based testing with React

I currently have some components that contain mui TextFields, and there are two specific scenarios for these components: One TextField is meant for LicenseCode and does not require a label. Additionally, there are several TextFields generated using t ...

What is the best way to utilize Link for navigation in React with Material UI?

const pages = ['home', 'menu', 'reservation']; <Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}> {pages.map((page) => ( <Link component={Link} to='/'>Home</L ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

Drag the label into the designated paragraph to copy the text. Click on the specific point to transfer the text

How can I copy the text from a label to a specific point by dragging it? <label id="text_to_be_copied" > i am a student </label> Below is a paragraph where I want to paste the copied text: <p> this is the content where I want to copy t ...

How to dynamically add a form to your website

Looking to dynamically insert a form on a page based on the value selected from a datalist, all without having to reload the entire page. <form action='#' method='get'> <input list="category" name="category"> <da ...

The element is automatically assigned an 'any' type due to the fact that a 'string' expression cannot be utilized to index the type 'typeof'

I am facing an issue that I am having trouble understanding. The error message reads as follows: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof The proble ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Encountering Karma Angular Error: Name 'X' Not Found

After executing Karma Start in my Angular project, I am encountering several errors. All the error messages highlight issues like 'Cannot find name Blob', 'Cannot Find name KeyboardEvent', 'Cannot find name HTMLElement', amon ...

Having trouble connecting v-model to vue-date-picker

My experience with the vue-date-picker and v-model for two-way data binding has been interesting. Initially, I set the value to a date (referred as startDate in this case) and printed the passed value (i.e. startDate) in the console. The initial value pa ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

What is the method to identify the key responsible for triggering a textbox input event?

Suppose there is a textbox on the webpage: <input id='Sub' type='text'> To capture each time the input changes, you can use the following code: sub = document.getElementById('Sub'); sub.addEventListener('input&a ...

What might be the reason my $q.defer().resolve is not functioning properly?

I have noticed an interesting behavior in my code. When I define a promise in the service and return it back (promise1 in this case), it does not resolve at all. However, when I define the promise in the controller (promise2), it works perfectly fine. Why ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

Utilizing statuses in Typescript React for conditional rendering instead of manually checking each individual variable

It's common for developers, myself included, to perform conditional rendering by checking variable values like this: import React, { useState, useMemo } from 'react' const Page = () => { const [data, setData] = useState<any[]>() ...

ng-repeat to display items based on dropdown choice or user's search input

Utilizing $http to retrieve JSON data for display in a table. I have successfully implemented a search functionality where users can search the JSON data from an input field. Additionally, I now want to include a feature that allows users to filter the JSO ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

Scrollbar width does not expand when hovered over

I am having trouble increasing the width of the scrollbar when hovering over it. However, I keep receiving an error in the console stating that 'scrollbar.addEventListener' is not a function. JAVASCRIPT setTimeout(function() { const scrollbar ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

Importing classes in ECMAScript 6 does not work properly, causing issues when running scripts

I am currently learning Selenium Webdriver. I am facing an issue where I can't run a script with imported classes, but I am able to run it without classes using import functions only. To execute it, I use babel-cli in the following manner: node ./babe ...