📜  typescript JavaScript time ago from datetime - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:24.180000             🧑  作者: Mango

TypeScript - JavaScript Time Ago from Datetime

In this article, we'll learn how to convert a given datetime into a human-readable time ago format using TypeScript or JavaScript.

Overview

Displaying human-readable time ago can be very useful for improving the user experience in a web application or mobile app. For example, instead of displaying a date like "2019-07-01 14:30", we can display "2 hours ago" or "yesterday" based on the current time.

To achieve this, we need to write a function that takes a datetime string or Date object as input and returns a time ago string as output. We'll use the Moment.js library to perform the datetime calculations.

Prerequisites

Make sure you have the following tools and libraries installed before starting:

  • Node.js
  • TypeScript (if you're using TypeScript)
  • Moment.js

You can install Moment.js using npm by running the following command:

npm install moment
Example Usage

Let's start by defining a function called getTimeAgo() that takes a datetime string as input and returns a time ago string.

import * as moment from 'moment';

function getTimeAgo(datetime: string): string {
  const now = moment();
  const inputDate = moment(datetime);
  const diff = now.diff(inputDate);
  const duration = moment.duration(diff);

  if (duration.asDays() > 1) {
    return inputDate.format("MMM D, YYYY");
  } else {
    return duration.humanize(true);
  }
}

The function first creates a moment() object for the current time, and another moment() object for the input datetime. It then calculates the difference between the two moments using diff(), and creates a duration object using moment.duration(diff).

Finally, it checks if the duration is greater than 1 day (using duration.asDays()), and returns either the formatted input datetime or a human-readable time ago string using duration.humanize(true).

To use this function, simply pass in a datetime string in the format YYYY-MM-DDTHH:mm:ss.sssZ. For example:

console.log(getTimeAgo('2022-11-05T12:00:00.000Z')); // "in 2 years"
console.log(getTimeAgo('2021-11-05T12:00:00.000Z')); // "a year ago"
console.log(getTimeAgo('2021-11-05T06:00:00.000Z')); // "5 hours ago"
console.log(getTimeAgo('2021-11-03T12:00:00.000Z')); // "Nov 3, 2021"
Conclusion

In this article, we learned how to convert a given datetime into a human-readable time ago format using TypeScript or JavaScript. We used the Moment.js library to perform the datetime calculations, and created a function that returns either a formatted datetime or a human-readable time ago string based on the duration between the input datetime and the current time.

By using this function in our web or mobile apps, we can provide a better user experience and make the information more easily understandable.