Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 901
user2297037 Avatar asked Jun 23 '26 17:06

user2297037


1 Answers

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.

like image 56
Sannon Aragão Avatar answered Jun 25 '26 08:06

Sannon Aragão



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!