user2297037
user2297037

Reputation: 1217

Angular serialize Date with specific format in POST request

I am new to Angular and I have several doubts about what is the best way to serialize a Date property of an object added to a POST request. Given the sample class

export class MyClass{
    public dateProperty: Date;
}

I have the following code in the service:

public addMyClass(myClass: MyClass): Observable<MyClass> {
    return this.http.post<MyClass>(this.apiBaseUrl, myClass);
}

I have to serialize Date in the following format 'yyyy-MM-dd hh:mm'. I considered different ways like defining a decorator (if possible), or overriding toJson() method, but I don't know if these are the only options or there is a better solution...

Upvotes: 7

Views: 2741

Answers (1)

Sannon Arag&#227;o
Sannon Arag&#227;o

Reputation: 351

Describing the problem that I had, I was at GMT+1, for instance, and would like to save just the date, something like "2019-04-28T00:00:00 GMT+01:00", and the JSON serialization was changing the date to "2019-04-27T23:00:00.000Z". Basically sending the wrong date, I guess you are facing something similar.

I found a wait to custom serialize everything at once for the whole project before sending it to the server, and it was by overwriting the toJSON function at the data object:

Date.prototype.toJSON = function() {
  return moment(this, moment.ISO_8601 ).format();
};

I'm also using moment.js. Hope it helps.

Upvotes: 8

Related Questions