Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Created December 21, 2016 10:38
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JonCatmull/e00afb1c96298a4e386ea1b5d091702a to your computer and use it in GitHub Desktop.
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.
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`;
}
}
@senorpatricio
Copy link

This is super helpful. Thanks!

@jwhenry3
Copy link

jwhenry3 commented Jun 8, 2018

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