Home > Net >  How can I avoid getting this error while parsing an input date with this format dd/mm/yyyy to yyyy-m
How can I avoid getting this error while parsing an input date with this format dd/mm/yyyy to yyyy-m

Time:09-18

I'm trying to parse a date with this format dd/mm/yyyy to yyyy-mm-dd with typescript in order to send the correct format to an API request. I'm using this function before sending the request:

formatDateForBE(date: string): string { 
    if (date) { 
      return this.datePipe.transform(date,'yyyy-MM-dd' ) 
    } 
    return null; 
}

and I get this error:

error

Can someone explain why and help me solve it? I'm using basically the same method to transform and show the dates that I get from the API (yyyy-mm-dd TO dd/mm/yyyy) and it works. Why is this one not working?

Thanks!

CodePudding user response:

DatePipe is used for converting a Date object to a string.

In your example, your are trying to use DatePipe to transform a string into a string. It is throwing this error because the transform function is expecting a Date object.

In order for this to work, you must first convert your date string to a Date object so that it can then be transformed into the string you want.

Try something like this:

  ngOnInit(): void {
    console.log(this.formatDateForBE("28/02/2022"));
    
  }

  formatDateForBE(dateString: string): string { 
    if (dateString) { 
      const splitDate = dateString.split('/');

      const date = new Date(
        Number(splitDate[2]),   // year
        Number(splitDate[1])-1, // month
        Number(splitDate[0])    // day
        );
        
      return this.datePipe.transform(date,'yyyy-MM-dd' ) 
    } 
    return null; 
  }
  • Related