Skip to content

Instantly share code, notes, and snippets.

@sunnyg1210
Created October 17, 2018 15:20
Show Gist options
  • Save sunnyg1210/4c1383a5ad4ef19e7abeca5999431bec to your computer and use it in GitHub Desktop.
Save sunnyg1210/4c1383a5ad4ef19e7abeca5999431bec to your computer and use it in GitHub Desktop.
Angular 2+ - Date to Time Ago Pipe
import { Pipe, PipeTransform } from '@angular/core';
/*
* Author: Sunny
* Convert Javascript Date into time ago format.
* example output: 20 seconds ago / 2 hours ago / 4 days ago etc
* Usage:
* date | timeAgo
* Example:
* {{ "2018-10-17T15:18:25.653Z" | timeAgo }}
*/
@Pipe({
name: 'timeAgo'
})
export class TimeAgoPipe implements PipeTransform {
transform(value: any, args?: any): any {
let date: any = new Date(value);
var seconds = Math.floor((Date.now() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) { return interval + " years ago"; }
interval = Math.floor(seconds / 2592000);
if (interval > 1) { return interval + " months ago"; }
interval = Math.floor(seconds / 86400);
if (interval > 1) { return interval + " days ago"; }
interval = Math.floor(seconds / 3600);
if (interval > 1) { return interval + " hours ago"; }
interval = Math.floor(seconds / 60);
if (interval > 1) { return interval + " minutes ago"; }
return Math.floor(seconds) + " seconds ago";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment