Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebApi DateTimeOffset serialize to Json/JavaScript (angular2)

I do not find a nice way to get a DateTimeOffset value to JavaScript (angular2). I am using WebApi (5.2.3) and angular2. On the wire I see the date as follow:

RecordModifiedAt : "2016-03-08T17:27:11.9975483+01:00"

JavaScript/angular2 does not recognize this as valid datetime value.

I do have options, but what direction should I go:

  • Server side: Newtonsoft.Json, ...
  • Client side: angular2, ...
  • Others?

Many thankx for your help!

like image 206
iwhp Avatar asked May 24 '26 01:05

iwhp


1 Answers

Thankx to PierreDuc feedback I have played around and I came to the following conclusion:

Since JSON does not support a Date datatype, I assume one has to make the conversion on the client side. I use the following 'pattern' (see http://codegur.com/36681078/angular-2-date-deserialization):

getTags() {
    return this.http.get('/api/tag/getAll')
        .map((response: Response) => this.convertData(response));
}

private convertData(response: Response) {
    var data = response.json() || [];
    data.forEach((d) => {
        // Convert to a Date datatype
        d.RecordModifiedAt = new Date(d.RecordModifiedAt);
    });
    return data;
}
like image 94
iwhp Avatar answered May 26 '26 13:05

iwhp



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!