Sirhc
8 January 2024 04:26
1
Hello

I am trying to calculate the days between two dates.

I have the following:

let date1 = new Date();

Then 2 days later, I set this:

let date2 = new Date();

I have tried:

let number_of_days = date2 - date1;

but I get this error: "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type."

Subtracting `date1`

from `date2`

will return the number of milliseconds between the 2 dates:

```
> var d1 = new Date()
2024-01-08T05:19:13.228Z
> var d2 = new Date()
2024-01-08T05:19:25.253Z
> d2 - d1
12025
```

When you say "...two days later..." I would suspect that the original `date1`

variable no longer exists as a Date object.

Sirhc
8 January 2024 05:46
3

shrickus:

```
d2 - d1
12025
```

It seems to work, but why does it underline the date in red in the function and give me this:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type

Ah, so the editor is giving that warning -- but the value is still calculated correctly?

In that case, you can get the value of each date in millis and then subtract those:
`date2.valueOf() - date1.valueOf()`

or use the unary `+`

operator to coerce those dates to integers, like this:
`+date2 - +date1`

(although the editor's syntax checker may not like that either)

Sirhc
8 January 2024 06:10
5
Editor didn't like the first solution, but the second one worked! Thanks!

i use this in a function node

```
msg.payload = dateToHowManyAgo(msg.payload)
return msg;
function dateToHowManyAgo(stringDate) {
var currDate = new Date();
var diffMs = currDate.getTime() - new Date(stringDate).getTime();
var sec = diffMs / 1000;
if (sec < 60)
return parseInt(sec) + ' second' + (parseInt(sec) > 1 ? 's' : '') + ' ago';
var min = sec / 60;
if (min < 60)
return parseInt(min) + ' minute' + (parseInt(min) > 1 ? 's' : '') + ' ago';
var h = min / 60;
if (h < 24)
return parseInt(h) + ' hour' + (parseInt(h) > 1 ? 's' : '') + ' ago';
var d = h / 24;
if (d < 30)
return parseInt(d) + ' day' + (parseInt(d) > 1 ? 's' : '') + ' ago';
var m = d / 30;
if (m < 12)
return parseInt(m) + ' month' + (parseInt(m) > 1 ? 's' : '') + ' ago';
var y = m / 12;
return parseInt(y) + ' year' + (parseInt(y) > 1 ? 's' : '') + ' ago';
}
```