How to Display Time Elapsed in a User-Friendly Format
Like the time displays on Stack Exchange, you can format JavaScript dates as strings indicating the time elapsed since a specific point. For instance:
To achieve this, you can utilize a function like the one provided below:
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"; }
As an example, if you set date to represent a time one day ago (24 hours), the function will return "1 day ago". Similarly, if you set date to represent a time two days ago (48 hours), the function will return "2 days ago".
The above is the detailed content of How to Display Time Elapsed in a User-Friendly Format?. For more information, please follow other related articles on the PHP Chinese website!