Trim date format PrimeNG calendar - remove timesta

2019-07-18 01:13发布

问题:

I have the following pushed into my reactive forms obj 2016-01-01T00:00:00.000Z but I want the following 2016-01-01.

Does anyone know of a built in function to achieve the above. I've searched the docs here but no luck. A .trim would of course work fine in a callback, but I'm wondering if anyone has done this before and knows a built in functionality.

Thanks.

UPDATE

To help others - this is how I solved it with the help of the answer below using primeng calender, reactive forms in angular. Using (onSelect) callback specific to primeNg Calendar

import { DatePipe } from '@angular/common';

<p-calendar
    #purchaseDateRef
    (onSelect)="handleSelect(purchaseDateRef)">
</p-calendar>


constructor(
    private datePipe: DatePipe
) {}

handleSelect(event: any) {
  // manipulate date object with help of DatePipe and setValue
  this.form.get('registrationFields.appliance.purchaseDate')
     .setValue(this.datePipe.transform(event.value, 'y.MM.dd')
  );
}

回答1:

You need to inject DatePipe in your component, as

constructor( private datePipe: DatePipe){}

than you can use wherever in the component the transform function

const formattedDate = this.datePipe.transformer(dateValue, 'build_in_date_format')

there are many build in formats, refer to the official documentation https://angular.io/api/common/DatePipe