Created
December 21, 2016 10:38
-
-
Save JonCatmull/e00afb1c96298a4e386ea1b5d091702a 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`; | |
} | |
} |
this only works for in the past, so I thought I would expand on it to add future relativity
getDuration(timeAgoInSeconds: number) {
for (let [name, seconds] of epochs) {
let interval = Math.floor(Math.abs(timeAgoInSeconds) / seconds);
if (interval >= 1) {
return {
interval: Math.abs(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';
let ago = timeAgoInSeconds < 0 ? '' : ' ago';
let _in = timeAgoInSeconds < 0 ? 'in ' : '';
return `${_in}${interval} ${epoch}${suffix}${ago}`;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is super helpful. Thanks!