How to calculate time difference between two timestamps?

I have a timestamp:

previousTime: "2022-09-10T08:40:00.000Z"

I want to calculate the time elapsed since the timestamp.
For example if the current time is

currentTime: "2022-09-10T10:44:00.000Z"

I want to output a string that looks like this:

2 hours and 4 minutes ago.

I do not care for days, months or years because the difference will never be more than a few hours, also I don't need to display seconds. Only hours and minutes.

In a function node you could do.

let current = new Date(msg.currentTime).valueOf();
let previous = new Date(msg.previousTime).valueOf();
let diff = current - previous;
let mins = Math.round((diff % 3600000)/60000);
let hours = Math.floor(diff/3600000)
msg.payload = hours > 0 ? `${hours} hours and ` : "";
msg.payload += `${mins} minutes ago.`
return msg;

[edit] made output deal with hours = 0. Also change round to floor for hours.

1 Like

Edit - @E1cid already answered.

A Function node can calculate the elapsed time in seconds and then convert it to hh:mm:ss eg "03:39:10"

function toTime(seconds) {
    var date = new Date(null);
    date.setSeconds(seconds);
    return date.toISOString().substr(11, 8);
}
let previousTime = new Date("2022-09-10T08:40:00.000Z");
let currentTime  = new Date();
let diffseconds = (currentTime.getTime() - previousTime.getTime())/1000;
msg.payload = toTime(diffseconds);
return msg;

I got the toTime() function from stackoverflow. There are some varied solutions there if you want to produce a different format.

1 Like

Thank you, worked perfectly :slight_smile:

Actually, it worked for one of my flows but not for another:

msg.payload.lastupdated: "2022-09-10T17:54:27.795"
msg.timestamp: "2022-09-10T18:04:23.173Z"
let current = new Date(msg.timestamp).valueOf();
let previous = new Date(msg.payload.lastupdated).valueOf();
let diff = current - previous;
let mins = Math.round((diff % 3600000) / 60000);
let hours = Math.floor(diff / 3600000)
msg.relativeTime = hours > 0 ? `${hours} hours and ` : "";
msg.relativeTime += `${mins} minutes ago.`
return msg;

This should output "10 minutes ago" but it outputs "2 hours and 10 minutes ago."

Why? My timezone is UTC+2 but both of the timestamps are in UTC so why does it add the two hours?

Might be because msg.payload.lastupdated time doesn't have a Z at the end...

Yes, it will assume local timezone if you don't give it one.

Yes, that was it! Added a "Z" to the end and now it works perfectly. Thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.