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.
2
Answers
The function
formatDaysHours
will format elapsed time in full days and full hours:If you need the nearest hour, you can replace
Math.floor(remainingTime/hours)
withMath.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.
I presume that the timestamps in the OP are local values, with the offset to be deducted to get UTC. I.e.
is
Given the timestamp format, they’ll need to be parsed manually. A library can help, but isn’t necessary for single cases.