Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Created December 21, 2016 10:50
Show Gist options
  • Save JonCatmull/998380fbb7fe23517790589652e881e3 to your computer and use it in GitHub Desktop.
Save JonCatmull/998380fbb7fe23517790589652e881e3 to your computer and use it in GitHub Desktop.
Relative date Pipe for Angular2 + TypeScript . Convert date or timestamp into relative date string e.g. "5 days ago" or to local date string e.g. "11/12/2016"
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
import { RelativeDatePipe } from './relative-date.pipe'; // https://gist.github.com/JonCatmull/e00afb1c96298a4e386ea1b5d091702a
const secondsInAday = 86400;
/*
* Turn Date into realtive date (e.g. "5 days ago") unless date is
* more than relativeMax days ago.
* Support any value supported by Date() object constructor
*
* Takes an relative max days argument that defaults to 10.
* Usage:
* value | smartDate:relativeMax
* Example:
* {{ 2016-12-09T13:13:43.572Z | smartDate:15}}
* formats to: '12 days ago'
* Example2:
* {{ 2016-12-09T13:13:43.572Z | smartDate}}
* formats to: '27/11/2016'
*/
@Pipe({name: 'smartDate'})
export class SmartDatePipe implements PipeTransform {
transform(dateStamp: number, relativeMax: number = 10): string {
let timeAgoInSeconds = Math.floor((Date.now() - new Date(dateStamp).getTime()) / 1000);
if (timeAgoInSeconds < relativeMax * secondsInAday) {
return new RelativeDatePipe().transform(dateStamp);
} else {
return new Date(dateStamp).toLocaleDateString('en-GB');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment