I am parsing a csv file which has a date column in dd/mm/yyyy format. The format of the date needs to be transformed to yyyy-mm-dd before saving it to the database. So I am using datepipe.transform method for this as below
this.datePipe.transform(x[this.csvcolumns.colDOB], 'yyyy-MM-dd','de')
By default the datepipe only accepts US date format which is mm/dd/yyyy. So for a date like 18/02/2000,the datepipe throws an error as below.
InvalidPipeArgument: 'Unable to convert "13/02/2012" into a date' for pipe 'DatePipe'
I've added the following configuration in app.module.ts.
import { registerLocaleData } from '@angular/common';
import localeDe from '@angular/common/locales/de';
registerLocaleData(localeDe);
So what is the best way to add LocaleId in DatePipe.transform as below
(method) DatePipe.transform(value: any, format?: string, timezone?:
string, locale?: string): string
Do i need to make any changes in the constructor for that? My constructor looks like below
providers: [DatePipe] })
export class BulkuploadPage implements OnInit {
constructor(private datePipe: DatePipe) { }
ngOnInit() {}
Personally, I think that using the datePipe transform outside of a custom datePipe is a bit of an anti-pattern.
This is the way I would do it using moment:
myFormattedDate = moment('13/02/2000', 'DD/MM/YYYY').format('YYYY-MM-DD');
//where..
myFormattedDate = moment(yourDate, currentFormat).format(desiredFormat);
and then you can use
<p>{{ someDate | date: 'YYYY-MM-dd' }}</p>
noting that you may not need to use the format section of the pipe depending on if you changed your default.
Working example: https://stackblitz.com/edit/angular-ps68n4?file=src%2Fapp%2Fapp.component.ts