📜  javascript get time ago with moment - Javascript (1)

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

Introduction to JavaScript Get Time Ago with Moment

When displaying dates on web pages, it's often useful to show the time elapsed since the date. This is commonly referred to as the "time ago". JavaScript's Moment library simplifies the process of generating this kind of output.

Getting Started with Moment

To begin using Moment, first include the Moment library in your project:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Moment is now available for use in your JavaScript code.

Formatting Time Ago Output

To format time elapsed between dates, Moment's fromNow() function can be used. This function returns a human-readable string representing the time since the given date. The output is automatically updated if the date is in the past, present or future.

const now = moment();
const date = moment('2022-01-01');

console.log(date.fromNow()); // "in a year"
console.log(now.diff(date, 'days')); // 331

In this example, the fromNow() method is used to display the time elapsed between today and January 1st, 2022. The diff() method returns a number of days between the two dates.

Customizing Time Ago Output

Moment offers a variety of options for customizing the time elapsed output. By default, fromNow() produces strings like "2 hours ago" or "3 days ago". Following is a list of methods that can be used to customize that output.

  • from(): sets the starting date for the calculation. Defaults to the current date.
  • to(): sets the end date for the calculation. Defaults to the date passed to fromNow().
  • excludeSeconds(): indicates if seconds should be included in the output. Defaults to false.
  • suffix(): sets the suffix to appear after the formatted string. Defaults to an empty string.
const now = moment();
const date = moment().subtract(10, 'minutes');

console.log(now.diff(date, 'seconds')); // 600
console.log(date.from(now)); // "10 minutes ago"
console.log(date.from(now, true)); // "10 minutes"
console.log(date.from(now, false)); // "10 minutes ago"

In this example, from() method takes the current date as the starting point for the calculation of the difference between the dates. The excludeSeconds() method has been used to exclude the seconds from appearing in the output of the from() method.

Conclusion

Moment is a powerful date and time library for JavaScript developers that makes working with dates and times much easier. Among other things, Moment provides an easy way to format 'time ago' output. By learning how to use Moment and its fromNow() method, you can create readable and useful output displaying the elapsed time between the dates.