Last active
January 8, 2020 18:54
-
-
Save luisramirezdev/be074d02bafa853a31609f384ef2ec39 to your computer and use it in GitHub Desktop.
Pipe Angular - Get custom date format for ux/ui desing: Date format 10 minutes ago / 10 hours ago / 10 days ago / 10 months ago / 10 years ago. More information: https://medium.com/@thunderroid/angular-date-ago-pipe-minutes-hours-days-months-years-ago-c4b5efae5fe5|-|{"files":{"date-ago.pipe.ts":{"env":"plain"}},"tag":"Angular"}
This file contains 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'; | |
@Pipe({ | |
name: 'dateAgo', | |
pure: true | |
}) | |
export class DateAgoPipe implements PipeTransform { | |
transform(value: any, args?: any): any { | |
if (value) { | |
const seconds = Math.floor((+new Date() - +new Date(value)) / 1000); | |
if (seconds < 29) // less than 30 seconds ago will show as 'Just now' | |
return 'Just now'; | |
const intervals = { | |
'year': 31536000, | |
'month': 2592000, | |
'week': 604800, | |
'day': 86400, | |
'hour': 3600, | |
'minute': 60, | |
'second': 1 | |
}; | |
let counter; | |
for (const i in intervals) { | |
counter = Math.floor(seconds / intervals[i]); | |
if (counter > 0) | |
if (counter === 1) { | |
return counter + ' ' + i + ' ago'; // singular (1 day ago) | |
} else { | |
return counter + ' ' + i + 's ago'; // plural (2 days ago) | |
} | |
} | |
} | |
return value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment