Home > Article > Web Front-end > How to Format Time Elapsed in Natural Language in JavaScript?
Formatting Time Elapsed in Natural Language
When displaying timestamps, it can be more user-friendly to express the elapsed time in natural language, such as "4 minutes ago" instead of "2023-03-08 14:05:03". This article demonstrates how to format JavaScript Date objects in this concise and readable manner.
The provided function, timeSince, calculates the difference between the current date and a given date. It then categorizes the elapsed time into years, months, days, hours, minutes, or seconds based on the number of seconds passed.
function timeSince(date) { var seconds = Math.floor((new Date() - date) / 1000); var interval = seconds / 31536000; if (interval > 1) { return Math.floor(interval) + " years"; } interval = seconds / 2592000; if (interval > 1) { return Math.floor(interval) + " months"; } interval = seconds / 86400; if (interval > 1) { return Math.floor(interval) + " days"; } interval = seconds / 3600; if (interval > 1) { return Math.floor(interval) + " hours"; } interval = seconds / 60; if (interval > 1) { return Math.floor(interval) + " minutes"; } return Math.floor(seconds) + " seconds"; }
For example:
var aDay = 24 * 60 * 60 * 1000; console.log(timeSince(new Date(Date.now() - aDay))); // "1 day ago" console.log(timeSince(new Date(Date.now() - aDay * 2))); // "2 days ago"
The above is the detailed content of How to Format Time Elapsed in Natural Language in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!