ERROR Error: InvalidPipeArgument: "12-01-2020 – 12-02-2020' to a date' for pipe 'DatePipe'

I am trying to concatenate two dates and assigning to variable but it is throwing an error
ERROR Error: InvalidPipeArgument: ‘Unable to convert “12-01-2020 – 13-02-2020” into a date’ for pipe ‘DatePipe’.where I am going wrong?

            this.startDate = this.datepipe.transform(response.projectStartDate, 'yyyy-MM-dd','es-ES');
            this.endDate = this.datepipe.transform(response.projectEndDate, 'yyyy-MM-dd','es-ES');

            response.gbRFEbean.projectDuration.value = this.startDate + "-" +this.endDate ;

2 thoughts on “ERROR Error: InvalidPipeArgument: "12-01-2020 – 12-02-2020' to a date' for pipe 'DatePipe'”

  1. locale is the fourth argument of the DatePipe transform and timezone is the third argument. Currently you have the locale as the third argument. I’d probably configure your locale like this (and the date pipe will automatically work for your locale without specifying):

    Missing locale data for the locale "XXX" with angular

    transform takes either a javascript date or an ISO date string so I’m guessing your dates (projectStartDate, projectEndDate) are strings that aren’t in the ISO format? The error message implies that one of those fields has the entire value of 12-01-2020 – 13-02-2020

    sample code with ISO date string

      startDate = '2020-01-12';
      endDate = '2020-02-13';
    
      formattedStartDate = this.datePipe.transform(this.startDate, 'yyyy-MM-dd');
      formattedEndDate = this.datePipe.transform(this.endDate, 'yyyy-MM-dd');
    
      constructor(private datePipe: DatePipe) {
        console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
      }
    

    Sample code with javascript date

      startDate = new Date('2020-01-12');
      endDate = new Date('2020-02-13');
    
      formattedStartDate = this.datePipe.transform(this.startDate, 'yyyy-MM-dd');
      formattedEndDate = this.datePipe.transform(this.endDate, 'yyyy-MM-dd');
    
      constructor(private datePipe: DatePipe) {
        console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
      }
    
    Reply
  2. The Date format: DD-MM-YYYY is invalid.

    You can try using :

    new Date("12-01-2020")
    

    It will give Invalid Date in chrome dev tools.

    Solution

    You can change the date format to MM-DD-YYYY and then pass it to datepipe.transform

    
    let date = response.projectStartDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
    this.startDate = this.datepipe.transform(date, 'yyyy-MM-dd','es-ES');
    date = response.projectEndDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
    this.endDate = this.datepipe.transform(date , 'yyyy-MM-dd','es-ES');
    
    Reply

Leave a Comment