Search code examples
angulardate-pipe

How to set input format of DatePipe


I want to just display month and year i.e. 09/24.

Now, I am receiving list of bills that are generated in last 3 months through an API where bill date format is 'dd-mm-yyyy'.

billDataList = [
                 {'id' = 101, 'bill_date': '17-08-2024'},
                 {'id' = 102, 'bill_date': '02-08-2024'},
                 {'id' = 103, 'bill_date': '26-09-2024'}  
               ]

In html template, list is on loop to display the id and date

<ng-container *ngFor="let bill of billDataList>
   <div class="bill-row-small">
      <span>{{bill['id']: {{bill['bill_date'] | date:'MM/yy'}}</span>
   </div>
</ng-container>

But it throws error:

InvalidPipeArgument: 'Unable to convert "28-09-2024" into a date' for pipe 'DatePipe'

This is may be because bydefault DatePipe takes format as 'medium' i.e. 'MMM d, y, h:mm:ss a'.

How to set input format of date as 'dd-mm-yyyy'


Solution

  • Angular's DatePipe expects a Date object, a number (milliseconds since UTC epoch), or an ISO string as input, that's the reason why inputs like "28-09-2024" lead to errors. This is to avoid ambiguities, for example, 02-08-2024 could either mean August 2nd or February 8th. You can transform your date string to a Date object with a custom pipe, before passing it to the date pipe:

    @Pipe({
      name: 'stringToDate',
      standalone: true,
    })
    export class StringToDatePipe implements PipeTransform {
      transform(value: string): Date {
        const [day, month, year] = value.split('-');
        return new Date(+year, month - 1, +day);
      }
    }
    

    And use it like the following:

    <span>{{bill['id']: {{bill['bill_date'] | stringToDate | date:'MM/yy'}}</span>