'How can I setup NSwag openapi2tsclient to generate correct Datetime init function?
I have a BE API (.NET 5.0) and FE in React. I am using NSwag to generate swagger.json file and then openapi2tsclient to convert it to typescript file. Everything works grate. I have a base entity with Datetime in UTC. It is translated to swagger.json file as:
"creationDate": {
"type": "string",
"format": "date-time"
},
This object is is initialized in my generated ts file like this:
export class BaseEntity implements IBaseEntity {
id!: string;
creationDate!: Date;
modifiedDate!: Date;
createdBy!: string;
modifiedBy!: string;
constructor(data?: IBaseEntity) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(_data?: any) {
if (_data) {
this.id = _data["id"];
this.creationDate = _data["creationDate"] ? new Date(_data["creationDate"].toString()) : <any>undefined;
this.modifiedDate = _data["modifiedDate"] ? new Date(_data["modifiedDate"].toString()) : <any>undefined;
this.createdBy = _data["createdBy"];
this.modifiedBy = _data["modifiedBy"];
}
}
static fromJS(data: any): BaseEntity {
data = typeof data === 'object' ? data : {};
let result = new BaseEntity();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["id"] = this.id;
data["creationDate"] = this.creationDate ? this.creationDate.toISOString() : <any>undefined;
data["modifiedDate"] = this.modifiedDate ? this.modifiedDate.toISOString() : <any>undefined;
data["createdBy"] = this.createdBy;
data["modifiedBy"] = this.modifiedBy;
return data;
}
}
But now my creationDate time is not longer in UTC but in GMT.
DateTime in DB: "2022-02-19 17:49:04.5360786"
Original time (as string from BE) before init: "2022-02-19T17:49:04.5360786"
creationDate after init function: Sat Feb 19 2022 17:49:04 GMT+0100 (Central European Standard Time)
For displaying time I am using react-moment package. When I don't use typescript and my datetime goes from BE as string I can use this code to display correct time:
<Moment utc local format="DD. MM. YYYY HH:mm">
{item.creationDate}
</Moment>
19. 02. 2022 18:49 //correct time
But when I use typescript item. And my creationDate is no longer just string but converted Date I am getting wrong time:
19. 02. 2022 17:49 // not correct time
Is there a way how can I setup NSwag openapi2tsclient to generate correct typescript file? Or what is a solution to such problem?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
