Error encountered in Typescript: The method date.getDate is not recognized as a

My goal is to retrieve the date from the first input control and the number of days from the other input controls, add them together, and assign the result to the third date control using TypeScript. However, I am encountering an error with the following code:

activeFrom: Date;
activeNoDays: number;

// UpdateExpiry Function is called by the textbox event
updateExpiry = (): void => {
    this.gDetailDS = this.gDetailForm.value;
    console.log("Expiry days:" + this.gDetailDS.activeNoDays);
    console.log(this.addDays(this.gDetailDS.activeFrom, this.gDetailDS.activeNoDays))
}

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

This is the HTML for the controls:

<input
    id="txtActivateFrom"
    type="date"
    min="rdMinDate"
    formControlName="activeFrom"
    class="form-control"
    value="{{ this.gDetailDS.activeFrom | date:'yyyy-MM-dd' }}"
    displayFormat="yyyy-MM-dd"
    useValueAsDate />

<input type="number"
    formControlName="activeNoDays" class="form-control"
    (change)="updateExpiry()"/>

Console Messages:

Expiry days:25
adding 25 days
2019-07-12

Despite trying everything, I am still facing this issue:

ERROR TypeError: date.getDate is not a function

Link: screenshot of the error appearing on the browser console

Answer №1

, I encountered a familiar issue while retrieving dates from a web API. My approach to resolving it involved the creation of a fresh Date object. To implement this solution, your function call can take the following form:
this.addDays(new Date(this.gDetailDS.activeFrom), this.gDetailDS.activeNoDays)

Answer №2

It is important to ensure that you create a Date object before attempting to pass it into the addDays function. When using Input.value with type="date", a string representation is returned, not a date object.

If you receive this information over JSON, you will still need to create a date object when using JSON.Parse()

fiddle: https://jsfiddle.net/o7y6u2zL/4/

let date = document.getElementById("start");
console.log(date.value);
console.log(typeof date.value);
let realDateObject = new Date(date.value);
console.log(typeof realDateObject)
<label for="start">Start date:</label>

<input type="date" id="start" name="trip-start"
       value="2018-07-22"
       min="2018-01-01" max="2018-12-31">

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

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

Leverage classes within components for effective dependency injection

Currently, I am working with Angular and have set up 1 component, 1 class, and 1 service in my project. The service is defined as an @Injectable class and properly configured in app.module.ts. @Injectable() export class MyService { My class receives the ...

basic template iteration in Angular 2

Need help creating a basic loop in HTML Here's an example: for(int i = 1; i < n ; i++){ //do something } I've tried various solutions but none seem to work for me. Here is one attempt: <li *ngFor='#loop of counter(5) ;#i= index&a ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

Incorporating an interface into a data property within a router using TypeScript and Angular

Within the app-routing-module.ts file, utilizing the data property allows us to include custom fields/variables as shown below: ... { path: 'admin-board', loadChildren: './admin-board/admin-board.module#AdminBoardPageModule', dat ...

Troubleshooting the issue with the HTTPClient get method error resolution

Currently, I am attempting to capture errors in the HTTP get request within my service file. Below is the code snippet: import { Injectable } from '@angular/core'; import { PortfolioEpicModel, PortfolioUpdateStatus } from '../models/portfol ...

Tips for managing the outcome of an HTTP Post request

I am currently working with Angular 2 and Node.js, attempting to incorporate braintree into my project, which has proven to be quite challenging. My current approach involves utilizing an HTTP Post request to send back the result object from the transacti ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...

Printing with Angular 2+ using ngx-print extension can be done manually by

Is there a way to print a div in Angular +2 using ngx-print, without automatically triggering the print function through a button attribute like ngxPrint? <button printSectionId="print-section" (click)="printProcedure()">print</button> ...

button listener event

Is there a way to verify if a button has been selected? <ul> <li *ngFor="let p of arrray; let i = index" > <button class="btn btn-success" (click)="onLoveIt(i)" >Love it!</button> &nbsp; </li> </ul> ...

Can you explain the distinction between an optional field and a union?

Is there a significant distinction between the following structures: { ok: boolean; } | { ok: boolean; error: any; } and: { ok: boolean; error?: any; } I have observed variance in the inferred types of frontend methods' return ou ...

The command 'ng' is not valid in this context, please make sure it is being used correctly within the program or batch file

After attempting to install angular-cli with npm install -g, I hit a roadblock. Next, I attempted to add it to the PATH under Environment Variables but encountered no success. https://i.sstatic.net/uhuhN.png https://i.sstatic.net/zHGBk.png ...

What methods can I use to eliminate redundant information from a dropdown selection?

<option *ngFor="let type of UserTypes; let i = index" [ngValue]="type.id"> <span>{{type.name}}</span> </option> I am looking for a solution to eliminate repeated data in the dropdown options. ...

Tips on deleting a nested JSON key?

Here is an example of my JSON structure: var data = [{ "ID" : 3, "discRec" : "Some sample record", "Tasks" : [{ "ID" : 7, ...

SharePoint Online / Angular - Issue: Unhandled Error: Zone is already loaded

I recently completed a project in Angular and integrated it into a SharePoint page using the Content Editor. Everything was running smoothly until yesterday, when I encountered an error while loading the page. zone-evergreen.js:42 Uncaught Error: Zone alre ...

Sanity.io's selection of schema field types for efficient and convenient

Hey there, guys! I recently started using Sanity.io and I'm curious whether there's a way to enhance my code efficiency and reuse certain fields across different schemas. I had an idea that goes something like this: cars.ts: export default { ...

Tips for managing an index signature in a basic object

I'm attempting to transform the received numerical status into a corresponding string for the user interface like this: {statuses[job.status]} const statuses = { 1: "Processing", 2: "Done", 3: "Aborted", 4: " ...

What is the method for retrieving properties from a generic in typescript?

In my code snippet, I am dealing with a generic type variable called data and I am looking for a way to access the values of its properties. The method hasOwnProperty isn't effective in this case due to the generic nature of the data. const data: T = ...