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

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

Ajax causing unreliable posts

I am facing an issue with sending and receiving data in my mobile application. I currently use the jquery $.post function, but it seems to be quite unreliable. Issue: Occasionally, about 1 out of 10 times, the POST request is sent successfully, but the ca ...

Applying ORM Drizzle in cases of conflict

Here's where I'm currently at: If I use onConflictDoNothing, the plan is to insert a new record into the database. However, if a record with the same userId and provider already exists, and the apiKey of the existing record is not equal to the ap ...

Generate checkboxes by utilizing the JSON data

Here is a snippet of my JSON data: [ { "type": "quant", "name": "horizontalError", "prop": [ 0.12, 12.9 ] }, { "type": "categor", "name": "magType", "prop": [ ...

The program is designed to only allow up to two images to be wrapped

I'm struggling with a short jQuery program that I need help with. The problem is, I can't seem to get it to wrap more than two images in the same row. My goal is to create a website that side-scrolls, and I thought this approach would be the simp ...

What is the process for defining default prop data in Next.js?

Currently, I am in the process of developing a React/Next app with CRUD functionality. In regards to the update form, I have included the code below which is responsible for fetching existing data and updating it via an API. However, there seems to be a ma ...

How to effectively manipulate nested arrays in JavaScript without altering their references

Welcome everyone, I've been working on a project using next.js and I've encountered an issue with filtering posts. The filter function works perfectly when the posts are in a simple array like ObjChild. However, I have another section on my site ...

Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling Receipt.query({freightBill: 123}), a query parameter such as freightBill ...

Incorporating Javascript jQuery functionalities from an external file

I have encountered an issue when trying to run my index.html file with the control.js file that I outsourced. It seems like they are not working together properly: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.c ...

What is the best way to arrange an array to display country data based on Covid cases in descending order rather than alphabetical order?

This particular code snippet retrieves Covid19 statistics data using an API. Currently, it displays the data for covid cases of all countries in Alphabetical order. However, I am looking to present the data in descending order, meaning that the country wit ...

Can you explain the functionality of this Observable in the context of this Angular 2 example?

I'm not too familiar with JavaScript/TypeScript and I have a question about how this code snippet works: onGet() { this.serverService.getServers() .subscribe( (servers: any[]) => this.servers = servers, // an array of anythin ...

Function not functioning as expected in NestJS MongoDB unique field feature

I am trying to set the "unique:true" attribute for the name property in my NestJS - MongoDB schema, but it is not working as expected by default. @Schema() export class User { @Prop() userId:string; @Prop({ type:String, required:true, } ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

As I iterated over the Vehicles API data, I encountered an issue while trying to access specific Vehicle information. I received an error message stating "Cannot read property 'id' of undefined

Exploring the realms of Angular, with some experience in older versions, I find myself faced with a challenge involving two APIs - "/vehicles" and "/vehicle/{id}". The process involves fetching data from "/vehicles", iterating through it to match IDs, the ...

Omit the <span> tag when exporting to XLS format

Currently, I have a functioning jQuery DataTable that utilizes the TableTools plug-in and includes <span> elements in one of the columns for each row. When clicking on the export button, my goal is to exclude or hide the <span> elements from t ...

Error: Uncaught TypeError - Unable to assign a value to the 'status' property

Hello everyone, I am currently facing an issue with validating the response from my server using Axios in VueJS. axios.post('/login', { email: this.email, password: this.password }).then(response => { if (response.status == 200) { $ ...

What is the best way to structure my protractor scenarios for effectively validating HTTP response errors?

My current setup involves using protractor to test the functionality of my Angular client, while the server is implemented using Python Google App Engine. In order to enhance my protractor test, I am looking to include an assertion on the http response ge ...