Home > Web Front-end > JS Tutorial > body text

How to Implement Stack Exchange's Time Display Formatting in JavaScript?

Patricia Arquette
Release: 2024-11-08 09:03:02
Original
284 people have browsed it

How to Implement Stack Exchange's Time Display Formatting in JavaScript?

Formatting Time Since: Replicating Stack Exchange's Time Display

The need to display time elapsed since a given point in time is commonplace in web applications. Many popular websites, such as Stack Exchange, employ a concise and informative format for displaying time since, like "4 minutes ago" or "1 year ago." Implementing a similar formatting method in JavaScript allows developers to provide a user-friendly and intuitive way of referencing past events.

To achieve this, we can leverage JavaScript's built-in Date object and a simple calculation to determine the elapsed time between two dates.

Implementation:

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";
}
Copy after login

Usage:

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"
Copy after login

This function calculates the difference between the current time and a given date, and then formats it as a string based on the elapsed time, ranging from seconds to years. The function operates by dividing the elapsed time by various intervals and rounding the result to the nearest integer.

By implementing this method, developers can easily display time elapsed in a consistent and user-friendly format, enhancing the user experience of their web applications.

The above is the detailed content of How to Implement Stack Exchange's Time Display Formatting in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template