Skip to content

Instantly share code, notes, and snippets.

@cozingo
Forked from JonCatmull/relative-date.pipe.ts
Created November 4, 2017 12:26
Show Gist options
  • Save cozingo/a7910531dfbd5451db4bc4167911a29c to your computer and use it in GitHub Desktop.
Save cozingo/a7910531dfbd5451db4bc4167911a29c to your computer and use it in GitHub Desktop.
Relative date Pipe for Angular2 + TypeScript . Convert date|timestamp into relative date string e.g. "5 days ago", "1 minute ago" etc.
import { Pipe, PipeTransform } from '@angular/core';
// Epochs
const epochs: any = [
['year', 31536000],
['month', 2592000],
['day', 86400],
['hour', 3600],
['minute', 60],
['second', 1]
];
/*
* Turn Date into realtive date (e.g. 5 days ago)
* Usage:
* value | relativeDate
* Example:
* {{ 86400 | relativeDate}}
* formats to: '1 day ago'
*/
@Pipe({name: 'relativeDate'})
export class RelativeDatePipe implements PipeTransform {
getDuration(timeAgoInSeconds: number) {
for (let [name, seconds] of epochs) {
let interval = Math.floor(timeAgoInSeconds / seconds);
if (interval >= 1) {
return {
interval: interval,
epoch: name
};
}
}
return {
interval: 0,
epoch: 'seconds'
};
};
transform(dateStamp: number): string {
let timeAgoInSeconds = Math.floor((new Date().getTime() - new Date(dateStamp).getTime()) / 1000);
let {interval, epoch} = this.getDuration(timeAgoInSeconds);
let suffix = interval === 1 ? '' : 's';
return `${interval} ${epoch}${suffix} ago`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment