angular show time ago

How to Show Time Ago in Angular

If you are working on an Angular project and want to display the time elapsed since a specific event, you can use the timeago-pipe extension. This will allow you to show the time ago in a human-readable format, such as "5 minutes ago" or "1 hour ago".

Installation

To get started, you will first need to install the timeago-pipe extension using npm:

$ npm install time-ago-pipe --save

Usage

Once you have installed the extension, you can use it in your Angular component by importing it and adding it to your declarations and imports arrays:

// Import the timeago pipe
import { TimeAgoPipe } from 'time-ago-pipe';

// Add the pipe to your declarations array
@NgModule({
  declarations: [
    AppComponent,
    TimeAgoPipe
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Once you have imported the pipe, you can use it in your HTML template by piping in a timestamp:

<p>Last updated: {{ lastUpdated | timeAgo }}</p>

The lastUpdated variable should be a timestamp, such as the result of Date.now().

Alternative Solution

Another way to show time ago in Angular is to use the moment.js library. This library provides a lot of useful functions for working with dates and times, including a fromNow() function that will show the time elapsed since a specific event.

To use moment.js, you will first need to install it using npm:

$ npm install moment --save

After installing the library, you can import it into your Angular component and use it like this:

// Import moment.js
import * as moment from 'moment';

// Get the current time
const now = moment();

// Calculate the time elapsed since a specific event
const lastUpdated = moment('2021-01-01T00:00:00');
const elapsed = moment.duration(now.diff(lastUpdated));
const timeAgo = elapsed.humanize(true); // "a year ago"

// Output the time elapsed
console.log(timeAgo);

This example gets the current time using moment(), calculates the time elapsed since a specific event using the diff() function, and outputs the result using the humanize() function. You can customize the output by passing options to the humanize() function, such as { s: 'second', m: 'minute', h: 'hour', d: 'day', w: 'week', M: 'month', y: 'year' }.

Either of these solutions will allow you to show time ago in your Angular project, depending on your specific requirements and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe