JC5577
JC5577

Reputation: 1169

How to resolve "Date" is not instanceof Date issue?

While troubleshooting an "Invalid date" in my ngx-bootstrap-bsDatepicker control and FormGroup, I've uncovered an issue with a date value on the object that I'm using (this.ts.startDateTime). When compared to a new Date() object.

08:11:03.723 ts-form.component.ts:240 HZyWZhwowB - this.ts.startDateTime 2019-07-16T20:18:24.9133333
08:11:03.724 ts-form.component.ts:242 HZyWZhwowB - testDate Wed Jul 17 2019 08:11:03 GMT-0400 (Eastern Daylight Time)
08:11:03.724 ts-form.component.ts:244 HZyWZhwowB - this.ts.startDateTime instanceof Date false
08:11:03.725 ts-form.component.ts:246 HZyWZhwowB - testDate instanceof Date true

The property in question is:

/**
  * Gets or sets the start date.
  */
startDateTime: Date;

It's pretty easy to see that the values are different. My object is data received from an HTTP Request to a WebAPI controller and the typescript interface is generated from models in the WebAPI. And for most of the application, the object's Date value works in its current state.

What is the best approach to resolve this issue within the Angular application--and to convert this value to an actual date?

Angular 5 - ASP.NET API
momentjs exists in the application, but not currently used in my component.

Upvotes: 0

Views: 530

Answers (1)

youri
youri

Reputation: 1160

ts.startDateTime is a string so you have to convert to a Date object:

let myDate = new Date(this.ts.startDateTime);

Remember to stick to a standard like you have (ISO 8601) to avoid to break the above code.

Upvotes: 1

Related Questions