0

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!

lyon
  • 23
  • 3
  • Does this answer your question? [Convert DD-MM-YYYY to YYYY-MM-DD format using Javascript](https://stackoverflow.com/questions/27087128/convert-dd-mm-yyyy-to-yyyy-mm-dd-format-using-javascript). There are more than one answer in this link. One of them could help you. – R. Richards Sep 16 '22 at 17:44
  • You are trying to convert a string to a date. You string value provided is not a valid date. You will have to provide a valid string format. –  Sep 16 '22 at 18:11

1 Answers1

0

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; 
  }
xJSx
  • 101
  • 3