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

How to Format Dates into Time-Elapsed Strings in JavaScript?

Patricia Arquette
Release: 2024-11-07 21:33:03
Original
1015 people have browsed it

How to Format Dates into Time-Elapsed Strings in JavaScript?

Time Since Formatting

In the realm of digital communication, it's commonplace to encounter timestamps that display the elapsed time since a specific event. Platforms like Stack Overflow exemplify this practice, providing users with convenient time-based information. This capability can be replicated in JavaScript, allowing you to format dates into strings that concisely convey the time lapsed.

The following solution harnesses the power of JavaScript's Date object to accomplish this task:

function timeSince(date) {
  const seconds = Math.floor((new Date() - date) / 1000);
  let interval;

  if (seconds / 31536000 > 1) {
    interval = Math.floor(seconds / 31536000);
    return `${interval} years`;
  } else if (seconds / 2592000 > 1) {
    interval = Math.floor(seconds / 2592000);
    return `${interval} months`;
  } else if (seconds / 86400 > 1) {
    interval = Math.floor(seconds / 86400);
    return `${interval} days`;
  } else if (seconds / 3600 > 1) {
    interval = Math.floor(seconds / 3600);
    return `${interval} hours`;
  } else if (seconds / 60 > 1) {
    interval = Math.floor(seconds / 60);
    return `${interval} minutes`;
  } else {
    return `${Math.floor(seconds)} seconds`;
  }
}

console.log(timeSince(new Date(Date.now() - (24 * 60 * 60 * 1000))));
console.log(timeSince(new Date(Date.now() - (2 * 24 * 60 * 60 * 1000))));
Copy after login

By leveraging this function, you can now easily convert JavaScript timestamps into user-friendly time-elapsed strings, mirroring the format adopted by platforms like Stack Exchange.

The above is the detailed content of How to Format Dates into Time-Elapsed Strings 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