amanhasnoname
amanhasnoname

Reputation: 276

How to Extract just the Date from Angular Material Datepicker

I have a reactive form and inside it I want to use the angular material datepicker. I've extracted the value from the datepicker using (dateChange) but the value it self is of the type object and included much more than what I need. Sun Aug 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

Is there away to get just the Month, Day, and the Year Aug 11 2019 without all the rest?

HTML

 <mat-form-field>
   <input matInput [matDatepicker]="dp" placeholder="Choose a date (dateChange)="updateDOB($event)" disabled>
   <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
   <mat-datepicker touchUi #dp disabled="false"></mat-datepicker>
 </mat-form-field>

TS (pretty simple at the moment)

updateDOB(dateObject) {
    console.log(dateObject.value);
  }

I've been reading a bunch of documentation but still can't figure it out. Any help is greatly appreciated.

Upvotes: 4

Views: 14356

Answers (4)

dzk008
dzk008

Reputation: 71

I had a very similar problem. I solved it using MomentDateAdapter and custom directive. Steps i took:

  1. install @angular/material-moment-adapter and moment.js
  2. add date format configuration :
export const DATE_FORMATS = {
  parse: {
    dateInput: ['MMM DD yyyy']
  },
  display: {
    dateInput: 'MMM DD yyyy',
    monthYearLabel: 'MMM yyyy',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM yyyy',
  },
};

First 'dateInput' matters how You should enter date (using keyboard for example) to be successfully parsed. Second 'dateInput' matters what format is used to dipslay date.

  1. Define providers:
    { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]},
    { provide: MAT_DATE_FORMATS, useValue: DATE_FORMATS }
  1. Create custom directive:
import {
  Directive,
  EventEmitter,
  HostListener,
  Input,
  Output,
} from '@angular/core';

@Directive({
  selector: '[setOutputDateFormat]',
})
export class DateFormatDirective {
  @Input('setOutputDateFormat')
  inputFormat = null;

  @Output()
  dateChangeWithFormat = new EventEmitter<string>();

  constructor() {}

  @HostListener('dateChange', ['$event'])
  onDateChange(event: any) {
    const dateFormatted = event.value.format(this.inputFormat);
    this.dateChangeWithFormat.emit(dateFormatted);
  }
}

Directive listens to 'dateChange' events, event.value attribute should contain date in moment object (as we switched to MomentDateAdapter at the beginning), so directive switches format to the desired ones and fires custom event with the desired format

  1. Lastly use the directive inside template providing custom format in 'outputDateFormat' property:
<mat-form-field>
  <input
    matInput
    [setOutputDateFormat]="outputDateFormat"
    [matDatepicker]="dp"
    placeholder="Choose a date"
    (dateChangeWithFormat)="updateDOB($event)"
    
  />
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker touchUi #dp disabled="false"></mat-datepicker>
</mat-form-field>

Example here: https://stackblitz.com/edit/angular-ivy-beufcw?file=src/app/app.component.ts

Now it seems that moment.js project has a legacy status, so better solution would be switch to luxon date adapter (it shouldn't be hard because luxon is moment.js successor)

Upvotes: 0

mEdi Han
mEdi Han

Reputation: 31

another way to do it:

dateObject.value.toLocaleString().substring(1, 10)

Upvotes: 1

Vinod Venugopal
Vinod Venugopal

Reputation: 41

Try this,

updateDoB(dateObject){
 console.log("DATE in dd/mm/yyyy",dateObject.toLocaleDateString())
}

Upvotes: 3

amanhasnoname
amanhasnoname

Reputation: 276

-Update-

I was able to come up with a work around for the problem. I stringified the object value and then trimmed the string to just included the date.

updateDOB(dateObject) {
    // convert object to string then trim it to yyyy-mm-dd
    const stringified = JSON.stringify(dateObject.value);
    const dob = stringified.substring(1, 11);
    this.applicant.contact[0].dob = dob;
  }

The result now comes out to 2019-08-11 which works for me.
If anyone has any other suggestions I'd still be happy to hear them.

Upvotes: 2

Related Questions