-1

I have this function to select the date which works fine

formatDateField(event: Date, formControl: string) {
    this.form
      .get(formControl)
      .patchValue(
        this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss")
      );
  }

I added a button to add the days to it using this code below but says undefined in developers tool > console:

  addDaysToDateForm(formName: string, days: number) {
    let formDate: Date = this.form.get(formName).value || new Date();
    formDate.setDate(formDate.getDate() + days);
    this.form.get(formName).setValue(formDate);
  }
  setTodayForm(formName: string) {
    this.form.get(formName).setValue(new Date());
  }

Any idea what's wrong with it?

termine
  • 55
  • 2
  • 8
  • 1
    I would advise to use a lib like `luxon` for that. – Matthieu Riegler Feb 09 '22 at 18:19
  • What does `this.form.get(formName).value` return? Does it really return a **`Date` object**? Your code seems to assume it does, but `value` in relation to DOM forms is a string. Of course, this may be some lib, but... – T.J. Crowder Feb 09 '22 at 18:20
  • 1
    Fundamentally, if `formDate` is really a `Date` object and `days` is really a number, then `formDate.setDate(formDate.getDate() + days)` **will** add `days` days to the date. So if you're not seeing that, then one of those two things isn't correct (`formDate` isn't a `Date`, or `days` isn't a number). – T.J. Crowder Feb 09 '22 at 18:21
  • 1
    I think `this.form.get(formName).value` returns a `string` instead of a `Date` object, so what @T.J.Crowder saying is true. – HassanMoin Feb 09 '22 at 18:27
  • Thank you @T.J.Crowder formDate is a Date object. formName is a string. how do i convert string to date in this code using this.form.get(formName).value ...? – termine Feb 09 '22 at 19:33

1 Answers1

0

We don't have Typed Forms (just yet) so values returned from form values aren't typed (as @T.J.Crowder says in the comments). You can convert the value returned from this.form.get(formName).value to a date by calling new Date() on it. i.e. new Date(this.form.get(formName).value)

laudebugs
  • 166
  • 1
  • 4
  • 2
    When suggesting using the built–in parser, it's also good to include a link to [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) :-) – RobG Feb 10 '22 at 02:44