0

So I need to get the number of days between the current date and the date we choose from a date picker.. How can i get the number of days onchoosing from date picker .

COMPONENT.HTML file

`<mat-form-field appearance="fill" class="example-form-field">
  <mat-label>Choose a date</mat-label>
  <input matInput [matDatepicker]="datepicker">
  <mat-hint>MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matIconSuffix [for]="datepicker"></mat-datepicker-toggle>
  <mat-datepicker #datepicker>
    <mat-datepicker-actions>
      <button mat-button matDatepickerCancel>Cancel</button>
      <button mat-raised-button color="primary" matDatepickerApply>Apply</button>
    </mat-datepicker-actions>
  </mat-datepicker>
</mat-form-field>`

For example using date picker if i choose date as 12/01/2023(which is 5 days from now).. I should get the result as 5 Days

Naveeth
  • 1
  • 1
  • To calculate the difference between now and a certain date, please check this SO-thread: https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript – kellermat Jan 07 '23 at 13:44
  • What's more, you could create a method `calculateNumDays()` in your TS and then trigger the calculation by `(dateChange)="calculateNumDays()"` – kellermat Jan 07 '23 at 13:45

1 Answers1

0

Per kellermat's comment, you can use this SO answer to handle it yourself, or use a library to do it.

Luxon is Moment's successor and what I generally recommend - let people that specialise in handling dates and time handle dates and times rather than reinventing the wheel yourself, getting it wrong, and ending up with a cube.

Here's a SO answer using Luxon:

const date1 = luxon.DateTime.fromISO("2020-09-06T12:00")
const date2 = luxon.DateTime.fromISO("2019-06-10T14:00")

const diff = date1.diff(date2, ["years", "months", "days", "hours"])

console.log(diff.toObject())

With the relevant diff doc page here.

Krenom
  • 1,894
  • 1
  • 13
  • 20