Search code examples
angularangular8localedate-pipe

Locale Date Angular 8 unable to convert


In my app.module.ts I added this code:

import { NgModule, LOCALE_ID } from '@angular/core';

import it from '@angular/common/locales/it';
import { registerLocaleData } from '@angular/common';

registerLocaleData(it);
//inside here I got all the necessary imports that I will not write here to avoid confusion
@NgModule({
  declarations: [
  ],
  imports: [
  ],
  providers: [{ provide: LOCALE_ID, useValue: "it-IT" }],
  bootstrap: []
})

Inside my html I have

<dd *ngIf="rec.DATECREATE" class="col-sm-8">{{rec.DATECREATE | date:'dd/MM/yyyy hh:mm:ss'}}</dd>

I get this error

Error: InvalidPipeArgument: 'Unable to convert "giu 22, 2021 11:14:38 AM" into a date' for pipe 'DatePipe'

if I try to replace giu with jun at runtime I don't get any error so the problem should be that it tries to use English instead of Italian. I think it does not read what I defined in my app.module.ts, how to fix this?


Solution

  • Method toDate is used to convert a string into the Date under the hood of the date pipe. Looking into its source code I'm surprised to see the locale we provide in the module configuration is not took into account. It checks:

    • if a string is actually a number (not your case)
    • if a string using is in ISO format without time (not your case)
    • if a string using is in ISO format with time (not your case)
    • fallsback to a constructor
      const date = new Date(value as any);
      if (!isDate(date)) {
        throw new Error(`Unable to convert "${value}" into a date`);
      }
      return date;
    

    So, it's up to us developers to convert the date from location-specific to ISO, number or a format that we are sure would be processed by the Date constructor.