Skip to content

Instantly share code, notes, and snippets.

@faustog94
Created August 30, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faustog94/4df1eb8da0a6457efe587667d2bc4723 to your computer and use it in GitHub Desktop.
Save faustog94/4df1eb8da0a6457efe587667d2bc4723 to your computer and use it in GitHub Desktop.
Fecha Relativa Pipe (Angular 2+)
/*
Basado en https://medium.com/@thunderroid/angular-date-ago-pipe-minutes-hours-days-months-years-ago-c4b5efae5fe5
*/
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'fechaRelativa',
pure: false
})
export class FechaRelativaPipe implements PipeTransform {
transform(value: Date, args?: any): any {
if (value) {
const seconds = Math.floor((+new Date() - + value) / 1000);
if (seconds < 29) // less than 30 seconds ago will show as 'Just now'
return 'Ahora mismo';
const intervals = {
'año': 31536000,
'mes': 2592000,
'semana': 604800,
'dia': 86400,
'hora': 3600,
'minuto': 60,
'second': 1
};
const plurals = {
'año': 'años',
'mes': 'meses',
'semana': 'semanas',
'dia': 'días',
'hora': 'horas',
'minuto': 'minutos',
'second': 'segundos'
};
const articuloSingular = {
'año': 'un',
'mes': 'un',
'semana': 'una',
'dia': 'un',
'hora': 'una',
'minuto': 'un',
'second': 'un'
};
let counter;
for (const i in intervals) {
counter = Math.floor(seconds / intervals[i]);
if (counter > 0)
if (counter === 1) {
return 'hace ' + articuloSingular[i] + ' ' + i ; // singular (hace un/una {intervalo})
} else {
return 'hace ' + counter + ' ' + plurals[i] ; // plural (hace {cant} {intervaloplural})
}
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment