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.
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.
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.
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?