Http Post Date Incorrect Fomat - Client problem

Viewed 155

I write angular 12 application send object with date (type Date, not string) property by httpClient.Post as bellow:

  public addPatient(): Observable<number> {
    let url = `${this.patientUrl}`

    var patientDetails = new patientDetails();
    patientDetails.birthDate = new Date();

    return this.http.post<number>(url, patientDetails, {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    });
  }

The request failed with error 400:

One or more validation errors occurred: The JSON value could not be converted to System.DateTime

In the network tab i really see that the date passed with incorrect string format (not JSON - ISO)

birthDate: "Sun Jun 12 2022"

enter image description here

Any idea about the reason?

1 Answers

Your date format is not correct. you should use ISO 8601

you should try the ISO format:

 public addPatient(): Observable<number> {
    let url = `${this.patientUrl}`
    var patientDetails = new patientDetails();
    patientDetails.birthDate = new Date().toISOString();

    return this.http.post<number>(url, patientDetails, {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    });
  }

You can read more about it here

Related