I'm trying to create post sharing web site. I want to create date ago pipe in angular.
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
name: 'messageTime',
pure: false
})
export class MessageTimePipe implements PipeTransform {
transform(value: Date, []): string {
var result: string;
// current time
let now = new Date().getTime();
// time since message was sent in seconds
let delta = (now - value.getTime()) / 1000;
// format string
if (delta < 10) {
result = 'jetzt';
} else if (delta < 60) { // sent in last minute
result = 'vor ' + Math.floor(delta) + ' Sekunden';
} else if (delta < 3600) { // sent in last hour
result = 'vor ' + Math.floor(delta / 60) + ' Minuten';
} else if (delta < 86400) { // sent on last day
result = 'vor ' + Math.floor(delta / 3600) + ' Stunden';
} else { // sent more than one day ago
result = 'vor ' + Math.floor(delta / 86400) + ' Tagen';
}
return result;
}enter code here
}
I trying like above code in my project. But it doesn't work corectly.
first create pipe class
ng g p pipes/DateAgo
Let's add these code,
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'dateAgo',
pure: true
})
export class DateAgoPipe implements PipeTransform {
transform(value: any, args?: any): any {
if (value) {
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
if (seconds < 29) // less than 30 seconds ago will show as 'Just now'
return 'Just now';
const intervals: { [key: string]: number } = {
'year': 31536000,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1
};
let counter;
for (const i in intervals) {
counter = Math.floor(seconds / intervals[i]);
if (counter > 0)
if (counter === 1) {
return counter + ' ' + i + ' ago'; // singular (1 day ago)
} else {
return counter + ' ' + i + 's ago'; // plural (2 days ago)
}
}
}
return value;
}
}
I think it's better to use one of the following packages to get a time ago functionality rather than creating your own, for few reasons like quick implementation
/ maintenance
/ new features and fixes
/ etc
ngx-timeago (would be my choice)
This one is having features that the other don't have e.g. i18n, live changes to the time ago text, etc.
time-ago-pipe
This is a simple 'pipe only' package, therefore it's light weight and simple to use.
ngx-moment
Suggestion: use this one only if you're already using moment.js in your app as this is about to become a legacy project and it will add a lot of weight to your bundle size (see comments below, thanks @ymerej and @Alexandre Germain).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With