Search code examples
angulartypescriptdate-pipe

DatePipe.transform show InvalidPipeArgument for 'dd-MM-yyyy'


Recently Angular DatePipe is showing an InvalidPipeArgument error but the String date seams to be correct. Can any one see some error? this is my code using Typescript and Angular 6

let datePipe: DatePipe = new DatePipe("es-ES");
let dia_sele: string = "";
                try {
                  let fecha_formateada = this.datePipe.transform('23-01-2019', 'dd-MM-yyyy','es-ES');
                  dia_sele = fecha_formateada;
                } catch (e) {
                  dia_sele = "";
                  console.log( "->err:" + e);
                }

And this is the error showing in console from Chrome Windows:

core.js:14597 ERROR Error: Uncaught (in promise): Error: InvalidPipeArgument: 'Unable to convert "23-01-2019" into a date' for pipe 'DatePipe'
Error: InvalidPipeArgument: 'Unable to convert "23-01-2019" into a date' for pipe 'DatePipe'
    at invalidPipeArgumentError (common.js:4013)
    at DatePipe.transform

Solution

  • Not sure what you are trying to achieve here. Because your input and output date have the same format.

    But the solution that will work if you need date in another format

    Why it is not working??

    In chrome '23-01-2019' is not a valid date string. Even

    new Date('23-01-2019')
    

    gives Invalid Date message in chrome (not checked in other browsers). You may try in console.

    Solution:

    So alternatively you may format the date with some other separator say / and then perform DatePipe transform on that date. More on formatting here

    Example :

    let myDate = "23-01-2019".replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3")
    let newDate = this.dp.transform(myDate, 'yyyy-MM-dd', 'es-ES');
    

    DEMO