I have several dates/times that I need to display, in local time - but I'd also like to have the time elapsed in days/hours for each date:
2024-11-22 04:03:59 (4 days 17 hours ago)
The data I have from the json file I am working with is:
dateUpdated | localTimeOffset
|
2024-11-21 12:05:32 | -05:00:00
2024-11-21 17:02:45 | 00:00:00
2024-11-22 04:03:59 | 11:00:00
These should all be around the same length of time ago, but obviously the local date/time doesn't make that obvious unless you factor in the offset; hence the request for time elapsed.
I am using vanilla JS.
Thanks in advance, if you require any further info please let me know.
The function formatDaysHours
will format elapsed time in full days and full hours:
const formatDaysHours = elapsed => {
const seconds = 1000;
const minutes = seconds * 60;
const hours = minutes * 60;
const days = hours * 24;
const elapsedDays = Math.floor(elapsed/days);
const remainingTime = elapsed - elapsedDays * days;
const elapsedHours = Math.floor(remainingTime/hours);
const pluralDays = elapsedDays == 1 ? "" : "s";
const pluralHours = elapsedHours == 1 ? "" : "s";
return `${elapsedDays} day${pluralDays}, ${elapsedHours} hour${pluralHours}`;
};
// Usage example:
const startTime = new Date('November 23, 2024 23:55:55 GMT+10:00');
const endTime = new Date();
const elapsed = endTime - startTime; //milliseconds
console.log(formatDaysHours(elapsed));
If you need the nearest hour, you can replace Math.floor(remainingTime/hours)
with Math.round(/* ... */)
. Note that multiplicity of nouns is taken into account: depending on the values, you can get “day” or “days”, “hour” or “hours”.
More importantly, look at my comments. Think of what is the end time of your intervals. If this is a really “present” time, you may want to handle timing events and update the view, say, every second. For hour accuracy, you would need a timing interval of about half an hour. Also, you should better store everything in UTC and present local time only locally in the UI.