5
votes

I'm new to TypeScript and AngularJS, and I'm trying to convert a date from my API that is something like:

"8/22/2015"

...to an ISO Date. The date is properly deserialized into a TypeScript property of type Date. However, when I try the following command (in typescript, and this.dateDisplay is of type string)

this.dateDisplay = formats.dateTimeValue.toISOString();

I get the error:

TypeError: formats.dateTimeValue.toISOString is not a function at dataFormatsTests.js:42 at processQueue (angular.js:14567) at angular.js:14583 at Scope.$get.Scope.$eval (angular.js:15846) at Scope.$get.Scope.$digest (angular.js:15657) at Scope.$get.Scope.$apply (angular.js:15951) at done (angular.js:10364) at completeRequest (angular.js:10536) at XMLHttpRequest.requestLoaded (angular.js:10477)

I've also been to this site and it says my browser supports the toISOString function.

So, my questions is: Why doesn't my browser, or angular, or whatever, recognize the toISOString function?

2
Are you sure that formats.dateTimeString is a Date object? It seems that it isn't Date object since toISOString isn't a function.Roope Hakulinen
Yeah, it's definitely a Date. Poor choice of property name on my part (I've been through a few iterations trying to get this to work, and I didn't update the property name). I'll edit my question to make it more clear. Thanks!JB123
What does it show if you do something like alert(formats.dateTimeString.toString()); or use console.error(..); if that suits better your usage.Roope Hakulinen
That's a type error, so it doesn't really matter whether it's actually a Date or not, since either way TypeScript doesn't think it is a Date. Go to where dateTimeValue is defined and make sure its type is Date. You can check the implementation afterwards.thoughtrepo

2 Answers

12
votes

Although the dateTimeValue was defined as a Date in TypeScript, it was being instantiated at runtime as a string because it was being pulled from the API. Therefore, the TypeScript would compile just fine, but when the javascript ran it was seeing .toISOString() being called against a string, not a Date.

1
votes

Moment.js creates a wrapper for the Date object.formats.dateTimeValue is not wrapper object. To get this wrapper object, simply call moment() with one of the supported input types. so convert it like this:

this.dateDisplay = moment(formats.dateTimeValue).toISOString();

I have solved my problem like above.