1

I want to make a POST request to an API. The API expects a date in the following format yyyy-MM-dd HH:mm:ss.SSS. I have a request object with an attribute of Type Date.

When I make the POST request via

this.http.post<ResponseObject>(url, objectWithDateAttribute, headers);

My API throws an error because the JSON format of the attribute of type date doesn't match.

How can I change the JSON format of the Date attribute when I make the POST request?

3 Answers 3

1

The API requires an ISO String you can obtain by calling toISOString() method on your date object.

Sign up to request clarification or add additional context in comments.

Comments

0

Your format is yyyy-MM-dd HH:mm:ss.SSS. let dateAttrib = new Date().toISOString().split('T').join(' ');

Comments

0

You can do it using angular DatePipe. You can convert the date object objectWithDateAttribute by looking at this sample example. Note the providers array and it should also be injected inside the constructor.

import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers : [DatePipe]
})
export class AppComponent  {

 someDate = new Date();
  constructor(private dp : DatePipe) {
     console.log(this.dp.transform(this.someDate, 'yyyy-MM-dd HH:mm:ss.SSS'))
  }
}

2 Comments

objectWithDateAttribute has multiple attributes. Only one of them is of type Date. Can I achieve with that pipe that every time objectWithDateAttribute is converted into JSON the specific date attribute has this format?
You should do formatting before building the request data. Probably inside that the setter method of that property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.