Home  >  Article  >  Web Front-end  >  How to Display Time Elapsed in a User-Friendly Format?

How to Display Time Elapsed in a User-Friendly Format?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-09 09:51:02398browse

How to Display Time Elapsed in a User-Friendly Format?

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:

  • 1 minute ago
  • 1 hour ago
  • 1 day ago
  • 1 month ago
  • 1 year ago

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn