Reputation:
So I'm getting Data from a C# Rest-Server. One value of the array is of the type Date. When I want to calculate with it for example:
let difference = date1.getTime() - date2.getTime();
I get the following error:
date1.getTime is not a function
I guess the error is, that Date
of Java is not the same as Date of Typescript.
Is there a way to convert a value of type Date
(Java) to type Date
(TypeScript)?
Or I'm I wrong and the error is caused by something else?
Upvotes: 1
Views: 4785
Reputation: 141
console.log((new Date().getTime() < new Date("2022-02-03").getTime()).toString());
This is how we do in Typescript
Upvotes: 0
Reputation: 3779
JSON has no date object. Usually a string is sent, take a closer look at what your API is providing. Sometimes it is a timestamp - depending on your GSON/Jackson/.. configuration. Timestamp needs a timezone offset too, therefore I'd prefer a string based format with included time zone. Usually it looks like this: "2018-03-10T09:06:08.068Z"
You can read this string into a JavaScript Date by passing it into the constructor: new Date(dateString)
. Now you have access to the methods.
Void already posted a vanilla JS implementation, but it gets even easier if you use a lib for that. I'd highly recommend date-fns. It accepts strings, so there is no need to create a new date:
differenceInMilliseconds(dateLeft, dateRight)
Docs: https://date-fns.org/v1.29.0/docs/differenceInMilliseconds
Upvotes: 1
Reputation: 36703
You need to convert the date to Date Object inorder to apply its method.
let difference = new Date(date1).getTime() - new Date(date2).getTime();
Upvotes: 4