I am getting the following error. I am not able to find out where exactly i went wrong.Can someone help me out with the solution
The code
function() {
this.devices.forEach(device => {
let lastConnect = device.lastConnection.split('+');
lastConnect = lastConnect[0] + 'Z';
let diff = Math.abs(new Date() - new Date(lastConnect));//getting error here
}
I have found out the issue.
The code you have written works only in Javascript
Math.abs(new Date() - new Date(lastConnect)) .
In order to make it work in Typescript, update the code as shown below:
Math.abs(new Date().getTime() - new Date(lastConnect).getTime());
Needless to say, Your code works correctly in Javascript, If you want to get the same result in Typescript, You have 3 options
(1) - With the help of valueOf
let diff = Math.abs(new Date().valueOf() - new Date(lastConnect).valueOf());
(2) - With the help of getTime
let diff = Math.abs(new Date().getTime() - new Date(lastConnect).getTime());
// or
let diff = new Date().getTime() - new Date(lastConnect).getTime();
(3) - With the help of any
let diff = Math.abs(<any>new Date() - <any>new Date(lastConnect))
The simplest answer would be
Math.abs(<any>new Date() - <any>new Date(lastConnect));
No need for Math.abs()
to answer this question...
Just using getTime()
method converts a Date into a number (Date.prototype.getTime()) so you can make the operation without that error
Check on this example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With