How to create a pipe that converts timestamps to relative time strings e g 2 hours ago

0 votes
can someone help me with this by including relevant code or example, How to create a pipe that converts timestamps to relative time strings (e.g., '2 hours ago')?
2 days ago in Angular by Nidhi
• 14,600 points
38 views

1 answer to this question.

0 votes

You can use the date-fns library for clean and accurate time difference formatting.

Relative Time Pipe using date-fns

1. Install date-fns

npm install date-fns


2. Create the Pipe

import { Pipe, PipeTransform } from '@angular/core';

import { formatDistanceToNow } from 'date-fns';

@Pipe({

  name: 'relativeTime'

})

export class RelativeTimePipe implements PipeTransform {

  transform(value: string | number | Date): string {

    if (!value) return '';

    return formatDistanceToNow(new Date(value), { addSuffix: true });

  }

}

3. Usage in Template

<p>{{ post.createdAt | relativeTime }}</p>

<!-- Output: 2 hours ago -->

answered 2 days ago by anonymous

Related Questions In Angular

0 votes
1 answer

How to create a custom directive that integrates with external charting libraries?

Compact Directive for External Chart Integration import { ...READ MORE

answered 2 days ago in Angular by anonymous
21 views
0 votes
1 answer
0 votes
1 answer

How to specify a port to run a create-react-app based project?

Hello @kartik, You could use cross-env to set the port, ...READ MORE

answered Jul 22, 2020 in Angular by Niroj
• 82,840 points
6,320 views
0 votes
1 answer

How to create a URL in the controller .NET MVC?

Hello @kartik, If you just want to get ...READ MORE

answered Jul 23, 2020 in Angular by Niroj
• 82,840 points
6,416 views
0 votes
0 answers

How do Observables improve API call handling in Angular?

With the help of an example, can ...READ MORE

Mar 3 in Angular by Nidhi
• 14,600 points
106 views
0 votes
0 answers

What’s the difference between Observables and Promises?

With the help of an example, can ...READ MORE

Mar 3 in Angular by Nidhi
• 14,600 points
76 views
0 votes
0 answers

What type of operation do RxJS operators allow for observables?

With the help of an example, can ...READ MORE

Mar 3 in Angular by Nidhi
• 14,600 points
85 views
0 votes
0 answers

When to use switchMap vs concatMap?

With the help of an example, can ...READ MORE

Mar 3 in Angular by Nidhi
• 14,600 points
111 views
0 votes
1 answer

How to develop a pipe that formats phone numbers based on locale?

You can use the libphonenumber-js library for ...READ MORE

answered 2 days ago in Angular by anonymous
23 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP